简体   繁体   中英

Display SQL Query Result using AJAX

I have a news feed on my site, onto which users can post posts. These posts can then be liked by other users (just like facebook for example).


The Problem
I would like to display the users, who liked a post using ajax. Whenever a certain element is hovered.
At the moment the users are correctly displayed but below every post, not just the one which contains the hovered element.
My attempt to solve the problem

 <!-- HOVER THIS --> <span class="likers small link"></span> <!-- DISPLAY LIKERS HERE --> <small class="displayLikers"></small> <!-- AJAX --> <script> $(function() { $(".likers").hover(function(){ $.ajax({ url: "get/likers", type: "GET", success: function(response) { $(this).closest('.displayLikers').html(response); } }); }); }); </script> 


I would be very thankful for any kind of help!

Inside the $.ajax , $(this) does not refer to $(".likers") just add $(this) to a variable and use it in the ajax response function;

$(function() {
    $(".likers").hover(function(){
        var likes = $(this);
        $.ajax({
            url: "get/likers",
            type: "GET",
            success: function(response) {
                likes.closest('.displayLikers').html(response);
            }
       });
    });
});

In your example the .displayLikers is a sibling so you should probably use next() . Moreover this will refer to the actual context of the success function, so you have to create a reference before.

$(function() {
    $(".likers").hover(function(){
        var self = $(this);
        $.ajax({
            url: "get/likers",
            type: "GET",
            success: function(response) {
                self.next('.displayLikers').html(response);
            }
       });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM