67

Here is some code I'd like to execute. I'd like to wait for AJAX response so I can return something from the server. Any way to achieve this?

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: function(data) {
            return data;
        }
    });

    //Wait for AJAX (???)
}

var response = functABC();
5
  • 3
    I don't understand. Why can't you use the success callback ? Maybe you're looking for api.jquery.com/jQuery.when
    – mddw
    Sep 27, 2012 at 6:17
  • 1
    I'd like to return the data to the response variable, where I called the function. However, the function returns null (because the AJAX call is asynchronous). Basically I want to know if it is possible to wait until the AJAX call is over to return the data.
    – OneMore
    Sep 27, 2012 at 6:20
  • So api.jquery.com/jQuery.when is what you're looking for.
    – mddw
    Sep 27, 2012 at 6:21
  • 2
    @user1691818: Returning the data is a really bad idea. Instead learn to think with callbacks. Cut and paste whatever code you need to execute in the callback function passed to success.
    – slebetman
    Sep 27, 2012 at 6:35
  • Some good answer is already provided. Check this one- stackoverflow.com/questions/14220321/…
    – IRSHAD
    Jul 29, 2017 at 19:25

8 Answers 8

60

When using promises they can be used in a promise chain. async=false will be deprecated so using promises is your best option.

function functABC() {
  return new Promise(function(resolve, reject) {
    $.ajax({
      url: 'myPage.php',
      data: {id: id},
      success: function(data) {
        resolve(data) // Resolve promise and go to then()
      },
      error: function(err) {
        reject(err) // Reject the promise and go to catch()
      }
    });
  });
}

functABC().then(function(data) {
  // Run this when your request was successful
  console.log(data)
}).catch(function(err) {
  // Run this when promise was rejected via reject()
  console.log(err)
})
3
  • 3
    With async=false being deprecated, this should be marked as the answer.
    – Moxtheox
    Aug 1, 2019 at 12:16
  • Yep. This is the way to go. it can take sometimes to understand promise but it is the way to do it. And it is lot better to pay some times learning it. Mar 18, 2020 at 13:41
  • This has helped me resolve an issue and understand how it works. Thanks :)
    – Tom
    Apr 10 at 10:30
56

New, using jquery's promise implementation:

function functABC(){

  // returns a promise that can be used later. 

  return $.ajax({
    url: 'myPage.php',
    data: {id: id}
  });
}


functABC().then( response => 
  console.log(response);
);

Nice read e.g. here.

This is not "synchronous" really, but I think it achieves what the OP intends.

Old, (jquery's async option has since been deprecated):

All Ajax calls can be done either asynchronously (with a callback function, this would be the function specified after the 'success' key) or synchronously - effectively blocking and waiting for the servers answer. To get a synchronous execution you have to specify

async: false 

like described here

Note, however, that in most cases asynchronous execution (via callback on success) is just fine.

3
  • 6
    async with value false is gone deprecated in most browser use cases. It may throw exceptions in newer version of browsers. See xhr.spec.whatwg.org/#sync-warning (applies to async parameter of xhr open method, which is what uses jQuery).
    – Frédéric
    Apr 21, 2015 at 10:58
  • 13
    If it is now deprecated, what is the solution?
    – JoeTidee
    Nov 11, 2016 at 12:52
  • this cannot be the answer, for deprecation. The answer should be this stackoverflow.com/questions/12615169/…
    – NicolaPez
    Nov 25, 2019 at 12:09
25

The simple answer is to turn off async. But that's the wrong thing to do. The correct answer is to re-think how you write the rest of your code.

Instead of writing this:

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: function(data) {
            return data;
        }
    });
}

function foo () {
    var response = functABC();
    some_result = bar(response);
    // and other stuff and
    return some_result;
}

You should write it like this:

function functABC(callback){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: callback
    });
}

function foo (callback) {
    functABC(function(data){
        var response = data;
        some_result = bar(response);
        // and other stuff and
        callback(some_result);
    })
}

That is, instead of returning result, pass in code of what needs to be done as callbacks. As I've shown, callbacks can be nested to as many levels as you have function calls.


A quick explanation of why I say it's wrong to turn off async:

Turning off async will freeze the browser while waiting for the ajax call. The user cannot click on anything, cannot scroll and in the worst case, if the user is low on memory, sometimes when the user drags the window off the screen and drags it in again he will see empty spaces because the browser is frozen and cannot redraw. For single threaded browsers like IE7 it's even worse: all websites freeze! Users who experience this may think you site is buggy. If you really don't want to do it asynchronously then just do your processing in the back end and refresh the whole page. It would at least feel not buggy.

1

nowadays I prefer using async function and await syntax

async function functABC(){
    await $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: function(data) {
            return data;
        }
    });

    //Wait for AJAX
}
1
async: true

When we request for some data to a server, then server will may take some time to return a response. Now During this time browser interpreter resume execution it will not wait for response and continues it's execution. So that response may print second and other code output will be print first. This happens due to async is set to true. Now question arise that what this parameter does. async means asynchronously. This attribute tells to interpreter that do not does execution sequentially.

async: false 

Means forcing that complete execution of this call/code first and then go for next. So it is depends on your requirement that how you use this attribute.

Example with async:

function ayncfunction() {
  $.ajax({
    url: 'abc.php',
    data: {id: id},
    async: true,
    success: function(repsonse) {
      return repsonse;
    }        
  });
}

Example without async

function ayncfunction(){
  $.ajax({
    url: 'abc.php', 
    data: {
      id: id
    },
    async: false,
    success: function(repsonse) {
      return repsonse;
    }        
  });
}
0

Try this code. it worked for me.

 function getInvoiceID(url, invoiceId) {
    return $.ajax({
        type: 'POST',
        url: url,
        data: { invoiceId: invoiceId },
        async: false,
    });
}
function isInvoiceIdExists(url, invoiceId) {
    $.when(getInvoiceID(url, invoiceId)).done(function (data) {
        if (!data) {

        }
    });
}
-1

use async:false attribute along with url and data. this will help to execute ajax call immediately and u can fetch and use data from server.

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        async:false
        success: function(data) {
            return data;
        }
    });
}
1
  • 6
    "Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active." also "with jqXHR is deprecated; you must use the complete/success/error callbacks. Sep 27, 2012 at 6:27
-3

Method 1:

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        success: function(data) {
            return data;
        },
        complete: function(){
              // do the job here
         }
    });
}

var response = functABC();

Method 2

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        async: false,
        success: function(data) {
            return data;
        }        
    });

   // do the job here
}
1
  • if a function return the data does that mean that the function wont return until the ajax is complete? My understanding was that it doesn't work this way, See method 1, will return immediately
    – Seabizkit
    Jul 30, 2017 at 14:09

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

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