Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery AJAX referencing $(this) within success function

I have a voting system which sends an id of the clicked item to a PHP script, the PHP updates the database and echos back the new vote counts via an JSON encoded array.

This is the jQuery:

$(".vote_up").click(function(){
    var id = this.id;
    var vote = $(this).attr("class");
    var data = "id=" + id + "&vote=" + vote;
    $.ajax
        ({
            type: "POST",
            url: "vote.php",
            data: data,
            cache: false,
            success: function(data)
            {
                for(var x in data) {
                         $(".votes_up").find(id).html(data[x].vote_up);
                         $(".votes_down").find(id).html(data[x].vote_down);
                }
            }
    });
});

So when i construct the item in the first place, i take the record ID in the database and set it as the items ID. So what i'm trying to do is reference the exact item that was clicked and set it's HTML to the data thats coming back from the PHP. I've checked in Firebug and I'm getting correct data back but the count of votes isnt changing. Any ideas?

This is the PHP for reference:

$query = "SELECT vote_up, vote_down FROM posts WHERE id = '".$id."'";
$result1 = mysql_query($query);
$output = Array();
while ($row = mysql_fetch_array($result1)){
    $output[] = Array(
        "vote_up" => $row['vote_up'],
        "vote_down" => $row['vote_down'],
    );
}
echo json_encode($output);
like image 354
benhowdle89 Avatar asked Feb 13 '11 02:02

benhowdle89


People also ask

How use this AJAX success?

"this" can be accessed inside jQuery AJAX success and error callbacks by setting the "context" configuration property for $. ajax() or changing context of AJAX callbacks using $. proxy() method. It is very common to access this inside jQuery AJAX's response callbacks (success or error).

What does success mean in AJAX?

What is AJAX success? AJAX success is a global event. Global events are triggered on the document to call any handlers who may be listening. The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds.

How can I get specific data from AJAX response?

You can't as it's asynchronous. If you want to do anything with it, you need to do it in a callback. How? Because it's asynchronous, javascript will fire off the ajax request, then immediately move on to execute the next bit of code, and will probably do so before the ajax response has been received.

What happens when one AJAX call is still running and you send an another AJAX call before the data of first AJAX call comes back?

Since Ajax calls are asynchronous, the application will not 'pause' until an ajax call is complete, and simply start the next call immediately. JQuery offers a handler that is called when the call is successful, and another one if an error occurs during the call.


2 Answers

If you just want this in the success: callback to refer to the element that was clicked, just set the context: property for the AJAX request.

$.ajax({
        context: this,  // set the context of the callbacks
        type: "POST",
        url: "vote.php",
        data: data,
        cache: false,
        success: function(data) {
           // now "this" refers to the element that was clicked
        }

You can test it by doing something a little more generic, like:

$(this).html("yep, it works");

... then if that works, consider that it doesn't really make sense to do .html() on the same element in a loop, because each time .html() overwrites the entire content.

Use .append() instead if you're appending data from the loop:

for(var x in data) {
         $(this).append(data[x].vote_up);
         $(this).append(data[x].vote_down);
}
like image 52
user113716 Avatar answered Oct 20 '22 22:10

user113716


Wouldn't:

$(".votes_up").find(id).html(...);

Really just need to be:

$('#' + id).html(..);
like image 45
Gregg Avatar answered Oct 20 '22 20:10

Gregg