views:

40

answers:

1

Hi, I use the $.post function to submit an ajax request as such:

$('.typeAform').submit(function(){
    $.post('/home', { somevar : 'somevalue' }, function(){
         //do something with the original form
    });
    return false;
});

I'd like to identify my form after submission from the $.post callback so I can do something with it (i.e. change its background color, delete it, etc...). Normally, I'd be able to call the form by its unique id that I know ahead of time, but here I don't have it - I am using a class for the form, not a single id.

Is there a way I can identify the form I just submitted without using a global variable (i.e. pass it to the callback somehow).

Thanks!

+2  A: 

EDIT:

Because the target of the submit event should always be the form itself, you could also use the target property of the event object, as in: e.target

$('.typeAform').submit(function( e ){
    $.post('http://apple.com', { somevar : 'somevalue' }, function(){
         // e.target references the form that was submitted.
         alert(e.target)
    });
    return false;
});​

If this gives you trouble, then there are other ways to avoid creating a variable if you don't want that.


Get the ID from the DOM element in the .submit():

var id = this.id;

So it would be:

$('.typeAform').submit(function(){
    var id = this.id;
    $.post('/home', { somevar : 'somevalue' }, function(){
         //do something with the original form
         // Use the "id" here
    });
    return false;
});

Or if you want the form itself, just reference this.

$('.typeAform').submit(function(){
    var theForm = this;
    $.post('/home', { somevar : 'somevalue' }, function(){
         //do something with the original form
         // Use the "theForm" here
         alert( theForm.id );
         $(theForm).someJQueryMethod()
    });
    return false;
});

Note that once you're inside the $.post callback, this no longer references the <form>. That's why we referenced it in a variable.

patrick dw
is there no way to find out from within the $.post what form was just submitted without setting a variable beforehand? something like `$.post('/home', {...}, function(event)(){ alert(event.form); })` or a similar syntax?
yuval
@yuval - Sorry, I didn't see this comment until just now. Yes, you could use `e.target`, giving the `submit()` handler a parameter named `e`. This will give you the form that was submitted. Either way will work. In both methods, the value of `e` or `this` is evaluated when the `.sumbit()` handler fires. I'll update.
patrick dw
Be sure to use `e.srcElement` if `e.target` is undefined for IE compatibility.
CD Sanchez
@Daniel - Not in this case. This is jQuery's `event` object which normalizes things such as the `target` property. See the *event properties* section here: http://api.jquery.com/category/events/event-object/
patrick dw
Cool, didn't know that. Nevermind then.
CD Sanchez