stergosz
stergosz

Reputation: 5860

jquery change this .post plugin to be able to use $(this) in callback

i use this plugin code for my ajax calls which i found on the net

jQuery.fn.postAjax = function(success_callback) {
  this.submit(function(e) {
    e.preventDefault();
    $.post(this.action, $(this).serialize(), success_callback);
    return false;
  })
  return this;
};

i altered it a bit so i can use it better with its usage to be like

$("#my_form_name").postAjax(function(data){
   //code here
});

the only problem with this code is that i can't use $(this) inside the callback and that is a problem...

how could i alter this plugin to be able to use $(this) ?

Upvotes: 0

Views: 47

Answers (1)

dfsq
dfsq

Reputation: 193311

Try this:

jQuery.fn.postAjax = function(success_callback) {
    this.submit(function(e) {
        e.preventDefault();
        $.post(this.action, $(this).serialize(), $.proxy(success_callback, this));
        return false;
    })
    return this;
};​

Read about jQuery proxy function.

Upvotes: 2

Related Questions