frenchie
frenchie

Reputation: 51997

consolidating $.ajax

I have several ajax call on my page and I want to consolidate them into one function.

For now I have this type of function in several places:

function AjaxCallOne () {

 //do something

 $.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: TheURL,
  data: "{'TheData':'" + JsonData + "'}",
  dataType: "json",
  cache: "false",
  success:...
  error:...
 });
}

I want to write a single function that'll be used for all ajax calls like this:

function MyGeneralAjaxCall(TheData, TheURL, TheSuccessFunction, TheErrorFunction) {
  $.ajax({ .... });
}

My question is this: if I do that and the user send two ajax calls, almost simultaneously, to the point where the second ajax call is made before the returning data of the first call comes back, will the success or error functions trigger for the the correct call. I'm worried that the success function that'll be executed won't be for the proper ajax call if the user triggers a second call before the first one is returned.

Thanks.

Upvotes: 1

Views: 134

Answers (2)

JayC
JayC

Reputation: 7141

First, There's no single, global set of callbacks for ajax requests. Each ajax invocation gets it's own set of callbacks.

Secondly: $.ajax({...}) is your MyGeneralAjaxCall... if you are thinking you need a set of default options, a better way would be to set up a

var  defaultoptions = { type: "POST", ...}  //put default options, mimetypes, etc, here 

(or something that returns that) and then wherever needed do:

var myajaxoptions = $.extend({},defaultoptions,myoverrides); 
$.ajax(myajaxoptions);

That's much more extensible. No need to make up "men in the middle". Your approach will work, but I could easily see more than one MyGeneralAjaxCall being created. If you can manage not creating 5 or more methods like that MyGeneralAjaxCall, I suppose you'll be doing ok, but it could get nasty real quick.

Upvotes: 0

ziesemer
ziesemer

Reputation: 28697

Your approach will work as you expect. Each success function, etc., that you pass in will be used individually by each associated AJAX call. (All of your parameters will be kept together.)

Upvotes: 3

Related Questions