P.Brian.Mackey
P.Brian.Mackey

Reputation: 44275

How can one synchronize nested ajax calls?

I have

function SomeFunc() {
  $.when($.ajax()).then(FunctionWhichDoesMoreAjax());
}

Now I need to wrap another call around this one.

$.when(SomeFunc()).then(FunctionWhichDoesMoreAjax2());

I tried modifying SomeFunc()

function SomeFunc() {
  return $.when($.ajax()).then(return FunctionWhichDoesMoreAjax());
}

But, this broke the functionality entirely. The IDE reports error

Expected Expression

at return FunctionWhichDoesMoreAjax());

How am I supposed to sync these up?

Upvotes: 0

Views: 584

Answers (2)

themhz
themhz

Reputation: 8424

You actually need to send an id to the server side controller that handles the Ajax request. A good way for usability, have in your mind that you can use a two position array in all cases. First position will have the id of the request and the second the data for example json data or anything else. When the server side finishes its job, it sends the response back to the page with in an array also the same pattern, id, data and your done. You can send async in your page without worrying to mix up the requests.

function request1(){
    data=getdata;
    arrData={1,data};
    ajaxsent(controler,data,onresponse1);

}

function request2(){
    data=getdata
    arrData={2,data};
    ajaxsent(controler,data,onresponse2);
}

function request3(){
    data=getdata;
    arrData={3,data};

    ajaxsent(controler,data,onresponse3);
}

function request4(){
    data=getdata;
    arrData={4,data};
    ajaxsent(controler,data,onresponse4);
}

function onresponse1(xml){
    synchronizer(xml);
}

function onresponse2(xml){
    synchronizer(xml);
}

function onresponse3(xml){
    synchronizer(xml);
}

function onresponse4(xml){
    synchronizer(xml);
}

function synchronizer(xml){
    switch(xml.id)
    case 1: dostuff;
    case 2: dostuff;
    case 3: dostuff;
    case 4: dostuff;

}

Upvotes: 0

dMb
dMb

Reputation: 9337

try this:

function SomeFunc() {
  return $.when($.ajax()).then(FunctionWhichDoesMoreAjax);
}

Upvotes: 3

Related Questions