1

I am using JQuery and AJAX to submit and process a form. Once the user submits the form, the html from the processing form (Using a success function) should get appended to the the current input. But what keeps happening, is that the html gets appended to all inputs on the page, not just the one being selected.

My Code:

    $(".comment-form").submit(function() {

        var dataString = $(this).serialize();
        $.ajax({  
            type: "POST",  
            url: "comment.php",  
            data: dataString,
            success: function(html) {
                $(".comment-input-wrap").append(html);  <-- The code in question
            }
        }); 

        $(this).find('.comment-input').val("");

        return false; 

    });

I Tried to use:

$(this).parent().append(html);

But I think the problem is that I can't use $(this) because it is outside the scope of the function. What can I do?

Thanks!

PSL
  • 123,204
  • 21
  • 253
  • 243
user2320500
  • 169
  • 3
  • 10

2 Answers2

6

Simplest approach would be to cache the element before ajax call and access it inside the callback.

You can do this way:

$(".comment-form").submit(function() {

    var dataString = $(this).serialize();
    var $this = $(this); //Cache it here
    $.ajax({  
        type: "POST",  
        url: "comment.php",  
        data: dataString,
        success: function(html) {
            $this.parent().append(html); //access the variable
        }
    }); 

    $(this).find('.comment-input').val("");

    return false; 

});

Or use context property of ajax.

 $.ajax({  
            type: "POST",  
            url: "comment.php",  
            data: dataString,
            context: this, //Set the context for callback
            success: function(html) {
                $(this).parent().append(html); //access it using the context itself.
            }
        }); 

or you can also use $.proxy

     $.ajax({  
            type: "POST",  
            url: "comment.php",  
            data: dataString,

            success: $.proxy(function(html) {
                $(this).parent().append(html); //access it using the context itself.
            }, this); // Set the context
        }); 

or using ecmascript5 function.prototype.bind

   $.ajax({  
            type: "POST",  
            url: "comment.php",  
            data: dataString,

            success: (function(html) {
                $(this).parent().append(html); //access it using the context itself.
            }).bind(this); // Set the context
        }); 
PSL
  • 123,204
  • 21
  • 253
  • 243
0

You could simply store $(this) in a variable:

{
    var $this = $(this);
    {
         $this.append(html);
    }
}
sp00m
  • 47,968
  • 31
  • 142
  • 252