8 months ago

[Solved] Cannot read html element data attribute

Posted 8 months ago by abarua

Hi, I am trying to read the postid attribute of the following article, but it is always null. I can print the content of the post without any problem. Thanks in advance!

<section class="row posts">
        <div class="col-md-6 col-md-3-offset">
            <header><h3>other posts</h3></header>
            @foreach($posts as $post)
            <article class="post" data-postid = "{{ $post->id }}">
                <p>{{ $post->content }}</p>
                <div class="info">Posted by {{ $post->user->username }} on {{ $post->created_at }}</div>
                <div class="interaction">
                    <a href="#">Like</a>
                    @if(Auth::user() == $post->user)
                        <a href="#" class="edit">Edit</a> |
                        <a href="{{ route('post.delete',['post_id' => $post->id]) }}">Delete</a>
        var token = '{{ Session::token() }}';
        var url = '{{ route('edit') }}';

Using the following javascript to print out in the console:

var postId = 0;

   var postBody = event.target.parentNode.parentNode.childNodes[1].textContent;
   postId = event.target.parentNode.parentNode.dataset['postid'];

      method: 'POST',
      url: url,
      data: {body: $('#post-content').val(), postId: postId, _token: token}
    .done(function (msg){

The route:

Route::post('/edit', function (\Illuminate\Http\Request $request)
        return response()->json(['message' => $request['postId']]);

Please sign in or create an account to participate in this conversation.