JQuery AJAX referencing $ (this) in success function

I have a voting system that sends the identifier of a clicked element to a PHP script, PHP updates the database and echoes back the new vote count through a JSON encoded array.

This is 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 create an element in the first place, I take the identifier of the record in the database and set it as the identifier of the elements. So what I'm trying to do is reference the exact element that was clicked and set it to HTML for data returned from PHP. I checked in Firebug and I get the correct data, but the number of votes does not change. Any ideas?

This is 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); 
+6
json jquery ajax php
source share
3 answers

If you just want this in the success: callback to refer to the element that was clicked, simply 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 verify this by doing something more general, for example:

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

... then if this works, think that there really is no point in doing .html() in one element in a loop, because .html() overwrites the whole content every time.

Use .append() instead if you are adding data from a loop:

 for(var x in data) { $(this).append(data[x].vote_up); $(this).append(data[x].vote_down); } 
+12
source share

will not:

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

In fact, you just need:

 $('#' + id).html(..); 
+1
source share

If you define a variable in the callback of the click () method, you can refer to it in your ajax callback. Something like this should do the following:

 $(".vote_up").click(function(){ // Assign the clicked element to a scoped variable... var target = $(this); 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) { // Then refer to it within your callback target.html(data[x].vote_up); target.html(data[x].vote_down); } } }); }); 
0
source share

All Articles