206

I've done some jQuery in the past, but I am completely stuck on this. I know about the pros and cons of using synchronous ajax calls, but here it will be required.

The remote page is loaded (controlled with firebug), but no return is shown.

What should I do different to make my function to return properly?

function getRemote() {

    var remote;

    $.ajax({
        type: "GET",
        url: remote_url,
        async: false,
        success : function(data) {
            remote = data;
        }
    });

    return remote;

}
Industrial
  • 41,400
  • 69
  • 194
  • 289
  • You code looks fine. what is it returning? Are there any js errors? – ShankarSangoli Jul 13 '11 at 20:34
  • 14
    I find it rather ironic - You're asking how to perform "Asynchronous JavaScript & XML" operation, synchronously. What you really need to perform is an "SJAX". – VitalyB Oct 02 '14 at 14:01
  • 4
    Note: the [spec](https://xhr.spec.whatwg.org/) has started deprecating synchronous AJAX requests. – Léo Lam Jan 31 '15 at 16:29
  • 2
    seems that the statement "[synchronous] will be required" indicates a lack of understanding of JavaScript engines, thus a poorly architected app. I would like to understand if there are cases where sync really is required. – pmont Feb 01 '15 at 15:23
  • 16
    @pmont `seems that the statement "[synchronous] will be required" indicates a lack of understanding of JavaScript engines, thus a poorly architected app.` Or a very good understanding: If you want to do an AJAX call `onbeforeunload`, using a synchronous request is actually the recommended way (as the browser window would be gone before the request returned otherwise). In any way he clearly says ` I know about the pros and cons of using synchronous ajax calls`... Maybe just believe him? – Stijn de Witt Jul 24 '15 at 11:15
  • @StijndeWitt Your example use of a synchronous request is actually a reason it's deprecated. Loading a synchronous request on browser unload will cause the users browser to hang when they want to close your page. This is a bad user experience and a bad design for your page. – teynon Jul 24 '15 at 14:56
  • @Tom May be, but in my book a bad design is only bad if there is a better design... Is there a better way to send a signal to the server `onbeforeunload` than doing a synchronous AJAX request? If not than I guess it means we are stuck using synch requests until the browser gods give us a better way. – Stijn de Witt Jul 28 '15 at 09:29
  • @Tom By the way do you have a source that this is deprecated. Asynch requests are *not* deprecated in jQuery (only their combination with `Deferred` is) and the only source for it as far as HTML goes that I've ever seen was from whatwg, which though influential, is not authorative when it comes to HTML. I'd like to see an authorative source. Even if asynch is 'officially' deprecated... so were `` and ``... – Stijn de Witt Jul 28 '15 at 09:32
  • @StijndeWitt - As per the post I put below: https://xhr.spec.whatwg.org/#the-open()-method, https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests. Google is your friend. Async requests are not deprecated. Synchronous requests are deprecated. Synchronous requests cause page hangs. You can still send ajax requests on unload. The sending process is synchronous until it sends the request. You won't necessarily receive the response. Receiving the response would be bad design, though, as I stated earlier. – teynon Jul 28 '15 at 13:10
  • @StijndeWitt I attempted to do an ajax request just to test. It does appear to be blocked by Chrome. I'm not sure what the real benefit of sending that request on page unload is though. If you want to know when the user left your page, you could do polling to get a general time, but really hindering the user experience for a tracking request is not really something we should be encouraging. I'm guessing Chrome blocks it for a reason. I would imagine its only a matter of time before they block sync requests as well. – teynon Jul 28 '15 at 13:49
  • @StijndeWitt you might be interested in considering the [Beacon API](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#Adapting_Sync_XHR_usecases_to_the_Beacon_API) as a preferred alternative to synchronous `onbeforeunload`. – Bondolin Mar 07 '19 at 14:25
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Heretic Monkey May 13 '19 at 16:57
  • Without synchronous AJAX on page unload, how would you solve this problem: You have a page open where users makes a series of changes to their data. Data should be automatically saved so user doesn't have to click a Save button. User chooses to close the browser, so now we need to auto-save the changes. With Beacon API data is sent to server, but a server-side validation error occurs which prohibits us saving the data and it requires user response in order to be fixed. This is a very real valid scenario but there is no way for the browser to handle it...! – TheStoryCoder Oct 16 '19 at 10:51

4 Answers4

331

As you're making a synchronous request, that should be

function getRemote() {
    return $.ajax({
        type: "GET",
        url: remote_url,
        async: false
    }).responseText;
}

Example - http://api.jquery.com/jQuery.ajax/#example-3

PLEASE NOTE: Setting async property to false is deprecated and in the process of being removed (link). Many browsers including Firefox and Chrome have already started to print a warning in the console if you use this:

Chrome:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

Firefox:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/

Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • 18
    Note that `responseText` always returns a string. If you are expecting JSON, wrap `$.ajax` with `JSON.parse`. – rgajrawala Jul 14 '14 at 14:54
  • 6
    Note: https://xhr.spec.whatwg.org/#the-open()-method Synchrounous requests are deprecated... – teynon Jun 24 '15 at 18:18
  • 7
    @Tom And so were the `` and `` tags. My recommendation: keep using these features so they won't go away. – Stijn de Witt Jul 24 '15 at 11:17
  • @StijndeWitt and tags were deprecated over semantics. Synchronous requests are deprecated for user experience. Synchronous requests will cause the browser to hang while the request takes place. Synchronous requests should be avoided. And I don't believe there is a case where synchronous requests are required over asynchronous requests. – teynon Jul 24 '15 at 14:53
  • 1
    as this locks the browser, makes sense to add a timeout : 5000 or so to the options. – commonpike Aug 01 '15 at 13:00
  • 1
    @usandfriends For parse string to object is more safely to use jQuery.parseJSON instead of JSON.parse http://stackoverflow.com/questions/10362277/jquery-parsejson-vs-json-parse – AntonE Nov 12 '15 at 08:53
  • I have a question about the deprecated facts. I use this, one time in a big ONE-PAGE-APP. Because, I have Handlebars, and I wish to load my templates one-by-one. So if the template does not exist (in memory), I do a synchronous AJAX and then I render it with the variables. If the template exists I just render it it the variable. How could I do the same behaviour withotu deprecated synchronous feature ? (I had thought about a timeout, but I find It really silly, and not optimized). Thank you, – vekah May 27 '16 at 11:53
  • Why should the browser hang if you do this in a separate thread? – jor Jul 25 '16 at 08:59
  • "Doesn't work on latest Chrome already (2016-04-26)." This is not a true statement. Chrome like many other browsers displays a stock warning indicating the feature is deprecated, but it most certainly still works. I tested it today as a result of this comment and I see it working as expected. – kamelkev Oct 03 '16 at 20:38
  • @kamelkev thanks, I've just updated it. (I didn't add the warning, someone else did, I just didn't verify it after the edit had already been approved.) Let me know if anything is still wrong. – Dogbert Oct 04 '16 at 07:51
  • 1
    There is a `responseJSON` now too – mask8 Oct 17 '17 at 21:25
  • As of 2019, Chrome has started experimenting with the removal of synchronous ajax requests. See https://stackoverflow.com/questions/55676319/ajax-synchronous-request-failing-in-chrome As the linked question states, for unload events, try using Beacon instead (https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API/Using_the_Beacon_API) – teynon May 16 '19 at 23:02
36

You're using the ajax function incorrectly. Since it's synchronous it'll return the data inline like so:

var remote = $.ajax({
    type: "GET",
    url: remote_url,
    async: false
}).responseText;
Jake
  • 2,471
  • 15
  • 24
19

how remote is that url ? is it from the same domain ? the code looks okay

try this

$.ajaxSetup({async:false});
$.get(remote_url, function(data) { remote = data; });
// or
remote = $.get(remote_url).responseText;
TheBrain
  • 5,528
  • 2
  • 25
  • 26
  • Yep! Same domain and everything. `remote_url` is defined properly and the AJAX call is properly carried out as mentioned (controlled with firebug). Just no return! – Industrial Jul 13 '11 at 20:35
2
function getRemote() {
    return $.ajax({
        type: "GET",
        url: remote_url,
        async: false,
        success: function (result) {
            /* if result is a JSon object */
            if (result.valid)
                return true;
            else
                return false;
        }
    });
}
honk
  • 9,137
  • 11
  • 75
  • 83
areyes.co
  • 37
  • 2