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();
OneMore
  • 1,139
  • 2
  • 9
  • 19
  • 3
    I don't understand. Why can't you use the success callback ? Maybe you're looking for http://api.jquery.com/jQuery.when/ – mddw Sep 27 '12 at 06: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 '12 at 06:20
  • So http://api.jquery.com/jQuery.when/ is what you're looking for. – mddw Sep 27 '12 at 06: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 '12 at 06:35
  • Some good answer is already provided. Check this one- https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – IRSHAD Jul 29 '17 at 19:25

8 Answers8

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)
})
MaartenDev
  • 5,631
  • 5
  • 21
  • 33
dome2k
  • 767
  • 6
  • 13
  • 3
    With `async=false` being deprecated, this should be marked as the answer. – Moxtheox Aug 01 '19 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. – Deepesh Thapa Mar 18 '20 at 13:41
  • This has helped me resolve an issue and understand how it works. Thanks :) – Tom Apr 10 '23 at 10:30
55

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.

Alexander Presber
  • 6,429
  • 2
  • 37
  • 66
  • 6
    `async` with value `false` is gone deprecated in most browser use cases. It may throw exceptions in newer version of browsers. See https://xhr.spec.whatwg.org/#sync-warning (applies to async parameter of xhr open method, which is what uses jQuery). – Frédéric Apr 21 '15 at 10:58
  • 13
    If it is now deprecated, what is the solution? – JoeTidee Nov 11 '16 at 12:52
  • this cannot be the answer, for deprecation. The answer should be this https://stackoverflow.com/questions/12615169/is-there-any-way-to-wait-for-ajax-response-and-halt-execution/45509714#45509714 – NicolaPez Nov 25 '19 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.

slebetman
  • 109,858
  • 19
  • 140
  • 171
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
}
Harun
  • 667
  • 7
  • 13
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;
    }        
  });
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
PQ RS
  • 41
  • 3
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) {

        }
    });
}
Prince Prasad
  • 1,528
  • 1
  • 16
  • 20
-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;
        }
    });
}
Anil Kumar
  • 165
  • 6
  • 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. – Michał Miszczyszyn Sep 27 '12 at 06: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
}
Snake Eyes
  • 16,287
  • 34
  • 113
  • 221
  • 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 '17 at 14:09