0

I am trying to use .ajaxSubmit(). I want to pass it the options object. I want to create this options object based on the user's behavior. So this is how I am doing it:

$('#my-form').ajaxSubmit(GetSearchAjaxFormOptions(param1, param2));

function GetSearchAjaxFormOptions(param1, param2) {
    return { target: '#results',
        data: GetData(),
        success: RunAfterAjaxSubmit(param1, param2)
    };
}

function RunAfterAjaxSubmit(param1, param2) {
    //    do stuff
}

Everything works fine except that RunAfterAjaxSubmit is called not only after the ajax call returns, but also before the ajax call is made at the following line:

success: RunAfterAjaxSubmit(param1, param2)

How do I change my code so it is only called after the ajax call is returned.

Many Thanks!

Michael Easter
  • 23,733
  • 7
  • 76
  • 107
Barka
  • 8,764
  • 15
  • 64
  • 91

2 Answers2

1

This sounds like a job for closures. The ajax success property expects a callback function which it will try to pump it's returned data into as the first param. so do something like this if you still want to use your param1 and param2

$('#my-form').ajaxSubmit(GetSearchAjaxFormOptions(param1, param2));

function GetSearchAjaxFormOptions(param1, param2) {
    return { target: '#results',
        data: GetData(),
        success: RunAfterAjaxSubmit(param1, param2)
    };
}

function RunAfterAjaxSubmit(param1, param2) {
    return function(ajaxData){
         //do stuff with param1 and param2 here as well as the ajaxData it returns if any
    }
}
Keith.Abramo
  • 6,952
  • 2
  • 32
  • 46
  • Thanks, I tried this. It didn't work. the code in function(ajaxData) is never reached. While RunAfterAjaxSubmit is reached. – Barka Oct 23 '11 at 00:55
  • Are you sure your ajax is returning with a success return code? – Keith.Abramo Oct 23 '11 at 00:57
  • pretty sure. My code works fine the way it is. The ajax results come thru and are displayed. I am just calling RunAfterAjaxSubmit once before the submit and once after the submit. i need to get the once before out. – Barka Oct 23 '11 at 04:05
  • looked at http://stackoverflow.com/questions/1969476/ajax-success-event-not-working and changed my submit to: success: function () { RunAfterAjaxSubmit(param1, param2)} It looks like this form solves the problem. Will test more tomorrow and update. – Barka Oct 24 '11 at 05:20
0

changing the success line to:

success: function () { RunAfterAjaxSubmit(param1, param2)}

fixes the problem

Barka
  • 8,764
  • 15
  • 64
  • 91