I am trying to use the response from a jQuery ajax request to set the innerHTML of a div with a certain id. This is the code I am using:
$(".show_comments").click(function(){
var articleName = $(this).closest("article").find(".articlename").attr('id')
$.ajax({
url: "commentView.php",
data: { 'articleName': articleName },
cache: false,
dataType: "html", // so that it will auto parse it as html
success: function(response){
$(this).closest("article").find(".comments").html(response);
}
});
however it doesn’t seem to be doing anything at all, I’ve tried googling around, but everything I can find says to do it the way I am doing it… I have tested in Firebug and the ajax request is giving me the exact response I want it too… But I just cant access this to set the innerHTML of the div to the response!
In your ajax success handler there is another scope and
thispoints to not what you think. So change your code to:What I’ve changed: I added
thatvariable that points tothisinstance and use it in the success handler instead.How would you debug it yourself: if you tried to output
console.log(this)andconsole.log($(this).closest("article").find(".comments"));you would see that it returns a wrong object (in first case) and nothing in second.