Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to block on ajax call (I want it to block)

Ajax uses callbacks, as it's Asynchronous.

I want my call to the remote URL block until there's some answer, exactly as in Ajax, but without the asynchronous part, or shall I say I want to make a JAX call.

Is there any technique to make the following happen (uses JQuery) (... solution with JQuery or anything else):

function get_data() {
    $.ajax({
        type : "POST",
        url : "/foo"
    }).done(function(data, textStatus, jqXHR) {
        return data;
    }).fail(function(jqXHR, textStatus) {
        return null;
    });
}

var data = get_data();
// process `data`

I'm just wondering - want to learn.

Actually there are times where blocking until a reply would fit fine. I'm not saying I want the browser to block, just the script runtime.

like image 695
Poni Avatar asked Aug 31 '12 10:08

Poni


1 Answers

You can simply set the async : false boolean when using jQuery (check the docs). Take note: As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the complete/success/error callbacks.

If you don't want to use jQuery or want to know what's going on under the hood, read this.

xmlhttp.open("GET","ajax_info.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

Do wonder why you don't want it to be async though...

like image 73
MarcoK Avatar answered Sep 21 '22 09:09

MarcoK