Answer the question
In order to leave comments, you need to log in
How to read data from database using ajax?
I am returning data from a database (news + comments). Comments have a "Like" button. After clicking on the button (AJAX), the rating is loaded into the database. Everything is working. How to return the number of likes without reloading the page for a comment?
Answer the question
In order to leave comments, you need to log in
I think that putting a form on each like element is tough.
I propose the following solution:
1) I will figuratively outline the picture of a like:
<div>
<i class="иконка сердечка" onClick="addLike({!! $comment->id !!})"></i>
<span c-id={!! $comment->id !!}>15</span>
</div>
function addLike(id) {
$.ajax({
url: '/comments/like',
dataType: 'json',
data: {
'id': id,
},
method: 'POST',
}).done(function(data) {
$("span[c-id="' + data.id + '").text( data.likes );
});
}
$comment = Comment::findOrFail($request->id);
$comment->likes += 1;
$comment->update();
return Response::json(['id' => $comment->id, 'likes' => $comment->likes]);
Each non- pivot/connecting/intermediate table (although they do have) usually has a unique key, most commonly referred to as an ID. Accordingly, no matter how you display comments, each of them must have some unique identifier. According to this identifier, respectively, send a request to the page / controller / method, with the ID of the comment that needs to be updated (add a like, add +1, etc.), using the same jQuery.post or jQuery. ajax. The data is an array with something like this:
{
id: 10, //ID комментария
action: 'like', //действие
data: 'Hello world' //доп. данные
}
Make a small API that returns a response in json format, for example, make a group of routes /api/methodname (for example, news_like).
And in the controller, send a request to the database through the model, do a return in json format, and in jquery, parse the json response itself, that's all.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question