1

I have this markup

<form action="..." id="form1" class="foo">...</form>
<form action="..." id="form2" class="foo">...</form>
...

and I have this Javascript code

$('.foo').ajaxForm({
    dataType: 'json',
    success: function (data) {
       // TODO: How do I get the form that triggered this?
       console.log( $(this) );
    }
});

As you can see in the Javascript code, I want to get the current form element when it submits and was succesful. Outputting $(this) didn't show me anything that points to the current form element.

How do I get the current form element inside the success function?

developarvin
  • 4,940
  • 12
  • 54
  • 100

4 Answers4

4

Assuming you are using jQuery Form Plugin

You can use 4th parameter

 success: function (data, statusText, xhr,  form ) {

References

success: Callback function to be invoked after the form has been submitted. If a 'success' callback function is provided it is invoked after the response has been returned from the server. It is passed the following arguments:

  1. responseText or responseXML value (depending on the value of the dataType option).
  2. statusText
  3. xhr (or the jQuery-wrapped form element if using jQuery < 1.4)
  4. jQuery-wrapped form element (or undefined if using jQuery < 1.4)
Community
  • 1
  • 1
Satpal
  • 132,252
  • 13
  • 159
  • 168
1

use :

context to pass this into success function

check following links : duplicate

$.ajax context option

How to pass Object context to jQuery.ajax JSONP callback?

Community
  • 1
  • 1
Mr7-itsurdeveloper
  • 1,631
  • 2
  • 17
  • 24
1

use beforeSubmit callback:

beforeSubmit: function(arr, $form, options){
    options.context = $form;
}

Here $form is the current form which is getting ajaxified and you can add the context to the options of the current ajaxForm with options.context = $form;. So now this will hold the current form which is getting submitted and you can get the current context.


something like this:

$('.foo').ajaxForm({
   dataType: 'json',
   beforeSubmit: function(arr, $form, options){
    options.context = $form;
   },
   success: function (data) {
     // TODO: How do I get the form that triggered this?
     console.log( $(this) );
   }
});
Jai
  • 74,255
  • 12
  • 74
  • 103
0

You can change you code into this:

var fooForm = $('.foo');
fooForm.ajaxForm({
    dataType: 'json',
    success: function (data) {
       // TODO: How do I get t

       console.log( fooForm);
    }
});

You cannot get $(this) because in success callback function, 'this' is point to windows.

In fact you code can be write into this style:

var fooForm = $('.foo');
fooForm.ajaxForm({
    dataType: 'json',
    success: successCallback
});
function successCallback(data){
    //'this' point to window : ) 
    console.log( fooForm);

}

Hope this would help. :)

Tyler.z.yang
  • 2,402
  • 1
  • 18
  • 31