Mirage
Mirage

Reputation: 31568

How to use the context variable in ajaxSetup with jquery

I have multiple forms on one page and i am submitting them via Ajaxform plugin like this

<td>  <form> form1 </form> </td>
<td>  <form> form2 </form>  </td>

var options = {
            target:        '.ajaxMessage',  
            dataType: 'json',  // pre-submit callback 
            success:     function(data, statusText, xhr, form){ myResponse(data,form)},
            context: { element: this},

            cache: false,
            delegation: true,
            type: 'POST'   }; 

            $(".rform").ajaxForm(options); 

In mY AjaxSetup , i have this

beforeSend:function(xhr, settings){

        $this = settings.context.element;       
        alert($this);

But its not working , alert says window object

Upvotes: 0

Views: 1004

Answers (1)

Thom Porter
Thom Porter

Reputation: 2609

When you are creating options, "this" is referring to window.

Not sure what you want this to refer to in beforeSend, but it would probably be easiest to just set it to a jQuery reference... like so:

<form id="form1">...</form>
<form id="form2">...</form>

and for your context object:

context: { element: $('#form2') },

Updated after Comment I see. This isn't elegant, but you can use the plugin's beforeSubmit callback to set a global variable to the form (which is passed into that callback,) and then access that in your beforeSend callback.

It might even be better to just put your code in beforeSubmit callback.

(this all assumes you're using this ajaxForm plugin.)

Updated with Example:

var options = {
  ...
  beforeSubmit: function(arr, $form, options) {
     // save the form somewhere we can get it later:
     $.MyActiveForm = $form;
  }

Now in your onSend function you can access $.MyActiveForm

But, I still think you're better off just doing whatever you were going to do in the onSend function, in beforeSubmit, unless you need to intervene at that particular point.

Upvotes: 3

Related Questions