@
@
@codeme2016-12-16 12:48:13
JavaScript
@codeme, 2016-12-16 12:48:13

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

3 answer(s)
V
Vlad, 2016-12-16
@Result007

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>

2) JavaScript function addLike(id):
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 );
        });
}

3) In the controller something like this:
$comment = Comment::findOrFail($request->id);
    $comment->likes += 1;
    $comment->update();

    return Response::json(['id' => $comment->id, 'likes' => $comment->likes]);

PS I apologize right away for the mistakes, I just wanted to convey the idea and it is probably possible to make various points more correctly.

E
Eugene Wolf, 2016-12-16
@Wolfnsex

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' //доп. данные
}

(*drawn very schematically)
get a response from the server, if you wish, you can check the response itself or the HTTP status and update the corresponding comment on the page, all with the same ID.
Everything is extremely simple :)
PS In the same way you can get data on the number of likes (or any other parameter) of any comment or other object. You send a request with an ID, you get a response.

H
honormgr, 2016-12-16
@honormgr

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 question

Ask a Question

731 491 924 answers to any question