[Solved] Cannot read html element data attribute

Posted 2 weeks 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>
                    @endif
                </div>
            </article>
            @endforeach
        </div>
    </section>
<script>
        var token = '{{ Session::token() }}';
        var url = '{{ route('edit') }}';
    </script>

Using the following javascript to print out in the console:

var postId = 0;

$('.post').find('.interaction').find('.edit').on('click',function(event){
   event.preventDefault();
   var postBody = event.target.parentNode.parentNode.childNodes[1].textContent;
   postId = event.target.parentNode.parentNode.dataset['postid'];
   $('#post-content').val(postBody);
   $('#edit-post').modal();
});

$('#modal-save').on('click',function(){
   $.ajax({
      method: 'POST',
      url: url,
      data: {body: $('#post-content').val(), postId: postId, _token: token}
   })
    .done(function (msg){
       console.log(msg['message']);
    })
});

The route:

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

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

Reply to

Use Markdown with GitHub-flavored code blocks.