kheya
kheya

Reputation: 7612

Asynchronous AJAX call problem

I have a jquery Ajax call function that I use to submit form to database to save. Also use that to get data from server and show to the user. When I post\save form data, I must show a result of the post to the user whether there was an error or not.

Everything works fine if I run in synchronous mode. I get the data if I want or get the result after posting using this single method.

But it seems not working in async mode.

How do I pass the data back to the caller? The web service returns the data correctly. See the alert() I have. It shows me the data.

How can I get data and show to user and post data and show result to user in async mode? Do I need to create 2 separate functions one for get and other to post?

Here is the function:

function MakeAjaxCall(svr, webmethod_name, op, btn, rslt, bGetData) {
   var data = "";
   var args = '';
   var l = arguments.length;
   if (l > 7) { for (var i = 7; i < l - 1; i += 2) { if (args.length != 0) args += ','; args += '"' + arguments[i] + '":"' + arguments[i + 1] + '"'; } }

   var surl = "http://<myserver>/" + svr + '.aspx';
   $.ajax({
      type: "POST",
      async: (op == "sync") ? false : true,
      url: surl + "/" + webmethod_name,
      data: "{" + args + "}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function ShowSuccess(res) {
         //alert('dfx res:'+res.d);//THIS SHOWS THE DATA FROM SQL CALL FINE
         data = res.d;
      },
      fail: function ShowFail(xhr) {         
         data = "ERROR";
      }
   });
}

Upvotes: 1

Views: 3987

Answers (1)

jball
jball

Reputation: 25014

Add a callback function? E.g.,

function MakeAjaxCall(svr, webmethod_name, op, btn,
                      rslt, bGetData, callbackFunction) {
   //removed for brevity

   var surl = "http://<myserver>/" + svr + '.aspx';
   $.ajax({
      //removed for brevity
      success: function ShowSuccess(res) {
         //pass the data to the callbackFunction
         callbackFunction(res.d);
      },
      //etc.
   });

Then just pass the function name (or anonymous function) into the MakeAjaxCall function, like so:

//anonymous function
MakeAjaxCall(svrVal, somewebmethod_name, opVal, btnVal,
                      rsltVal, bGetDataVal, function(data) { alert(data); });

//named function
MakeAjaxCall(svrVal, somewebmethod_name, opVal, btnVal,
                      rsltVal, bGetDataVal, alert)

Upvotes: 3

Related Questions