0

hey, i'm trying to change the html of a div after an ajax request, the ajax request works. the data is correct but the selector can't seems to find the div

here's the code

$(".home .up_0").click(function(){
  $.post("includes/vote.php",   
        {
         truc : $(this).attr("id")
        },
       function(data){ 
        if(data=='fail') 
        {
          alert("Error.");
        }
        else
        {
          $(this).parents('.home').find('.score_neutre').html(data);
        }
       }
  );
});
Doug Neiner
  • 65,509
  • 13
  • 109
  • 118
David 天宇 Wong
  • 3,724
  • 4
  • 35
  • 47
  • We'll need to see some of your HTML code to figure out why it doesn't work. – Topher Fangio Dec 17 '09 at 16:19
  • Can you post the corresponding HTML code? – Shawn Steward Dec 17 '09 at 16:19
  • 1
    `this` probably doesn't exist in the callback function. There surely is a workaround for this in JQuery but I don't know what it's called. – Pekka Dec 17 '09 at 16:22
  • 1
    I think Pekka is headed in the right direction. I suggest possibly capturing `this` and storing it for use later. – Sneakyness Dec 17 '09 at 16:23
  • Also important, what browser are you using? .html() has problems under certain browsers. http://stackoverflow.com/questions/317095/how-do-i-add-options-to-a-dropdownlist-using-jquery – ryanday Dec 17 '09 at 16:23

3 Answers3

6

This is probably because this isn't what you expect within the inner function. You'll need to add a variable to store the reference:

$(".home .up_0").click(function(){
  var this_obj = $(this);
  $.post("includes/vote.php",   
        {
         truc : $(this).attr("id")
        },
       function(data){ 
        if(data=='fail') 
        {
          alert("Error.");
        }
        else
        {
          this_obj.parents('.home').find('.score_neutre').html(data);
        }
       }
  );
});
DMI
  • 6,843
  • 2
  • 24
  • 25
1

Your problem is that this is not pointing to what you think it is.

Do this:

$(".home .up_0").click(function(){
  var $this = $(this); // Cache the current `this` as a jQuery wrapped DOM element
  $.post("includes/vote.php",
       { truc : $(this).attr("id") },
       function(data){ 
          if(data=='fail') {
              alert("Error.");
          } else {
              // Reference the cached variable `$this`
              $this.parents('.home').find('.score_neutre').html(data);
          }
       });
});
Doug Neiner
  • 65,509
  • 13
  • 109
  • 118
0

It could have something to do with this not representing the $(".home .up_0") element since it's inside the function(data){} success function?

Try adding a dummy div, id="Test" and inside the success function use:

£('#Test').html(data);

This will tell you if it's working. If it is you'll need to use a var to store what this represents.

Fermin
  • 34,961
  • 21
  • 83
  • 129