How can I stop $ .post in jQuery working asynchronously?

I have the following calls:

getData(0);
getData(1);
getData(2);

They call the javascript function:

function getData(Code) {
  $.post('/adminA/GetData',
                { Code: Code },
  function (data) {

The problem is that my data is returning out of order. Is there a way to return the data in order?

+5
source share
5 answers

Calling these three ajax requests synchronously freezes your browser. You will be better off using jQuery Deferred objects. Try the following:

function getData(Code) {
    return $.post('/adminA/GetData', { Code: Code }, function (data) {/*etc.*/});
}

getData(0).done(function() {
    getData(1).done(function() {
        getData(2);
   });
});

Adding

You should also consider combining your calls into one and changing the server logic to handle it. This will ultimately be faster than three queries:

function getData(firstCode, secondCode, thirdCode) {
    $.post('/adminA/GetData', {
        codeOne   : firstCode,
        codeTwo   : secondCode,
        codeThree : thirdCode
    }, function (data) {/*etc.*/});
+6
source

Another alternative is to use ajaxSetup

function getData(Code) {
  $.ajaxSetup({async: false});
  $.post('/adminA/GetData',{ 
        Code: Code },  function (data) {
         // Do Something
        }); 
   $.ajaxSetup({async: true}); //So as to avoid any other ajax calls made sybchrounously
}
+17
source

$.ajax async false.

+9

$.ajaxSetup({ asynch: false }) jQuery:

jQuery.ajaxSetup()

 < >   options /,   Ajax-.  . >

ajax jQuery.

+3

, $.ajax async false. , . ajax, . , , .

- :

 function getData(Code) {
    $.post('/adminA/GetData',
                { Code: Code },
                function (data) {
                    getData(Code+1)
                });
 }

, - , .

0
source

All Articles