1

I have two ajax call in my jquery code, I would need one value from the first one to be used in second ajax call. But I observed that the second ajax code is running first.

$.ajax({
        url: "https://test/_api/Web/Lists/GetByTitle('abc')/items?$select=Title,sub/Title&$expand=sub",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {
        for(var i=0;i<data.d.results.length;i++)
        {
          if(data.d.results[i].Title == versionTitle)
          {
          varSubsystem = data.d.results[i].Sub.Title;
          }         
        }                  
        },
        error: function ( xhr, status, error) {
      alert( " xhr.responseText: " + xhr.responseText + " //status: " + status + " //Error: "+error ); 
        }
    }); 


$.ajax({
        url: "https://test/_api/Web/Lists/GetByTitle('Mapping')/items?$select=Title,Team/Title,Sub/Title,Subsys/Title,Subsys/Team_x0020_Member&$expand=Sub,Team,Subsys",
        type: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function (data) {          
        for(var i=0;i<data.d.results.length;i++)
        {
          if(data.d.results[i].Sub.Title == varSubsystem && data.d.results[i].Team.Title == teamName)
          {
          owner = data.d.results[i].Subsys.Team_x0020_Member;
          }

        }

            console.log(data.d.results);
        },
        error: function ( xhr, status, error) {
      alert( " xhr.responseText: " + xhr.responseText + " //status: " + status + " //Error: "+error ); 
        }
    });

How would I make sure that the second ajax code runs after the first one?

1
  • 1
    You put it in the success of the first one or use promises (as you do with all asynchronous javascript code..) Jan 13, 2016 at 7:17

1 Answer 1

1

The A in Ajax means Asynchronous. So as Robert says, chain with Promises or put the second call inside the Success Callback function of the first

Note: You could solve your problem by setting the property async:false in the first Ajax call... it makes the call NOT asynchronous. Only use it when you know what it does (or do not care about performance)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.