Synchronous – Script stops and waits for the server to send back a reply before continuing. There are some situations where Synchronous Ajax is mandatory.
In standard Web applications, the interaction between the customer and the server is synchronous. This means that one has to happen after the other. If a customer clicks a link, the request is sent to the server, which then sends the results back.
Because of the danger of a request getting lost and hanging the browser, synchronous javascript isn’t recommended for anything outside of (onbefore)unload event handlers, but if you need to hear back from the server before you can allow the user to navigate away from the page, synchronous Javascript isn’t just your best option.
Synchronous AJAX function Example using GET.
function getFile(url) {
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
AJAX.open("GET", url, false);
AJAX.send(null);
return AJAX.responseText;
} else {
return false;
}
}
var fileFromServer = getFile('http://www.phpmind.com/om.txt');
Synchronous AJAX function Example using POST.
function getFile(url, passData) {
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
AJAX.open("POST", url, false);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.send(passData);
return AJAX.responseText;
} else {
return false;
}
}
var fileFromServer = getFile('http://www.phpmind.com/data.php', sendThisDataAsAPost);
Asynchronous – Where the script allows the page to continue to be processed and will handle the reply if and when it arrives. If anything goes wrong in the request and/or transfer of the file, your program still has the ability to recognize the problem and recover from it.
Processing asynchronously avoids the delay while the retrieval from the server is taking place because your visitor can continue to interact with the web page and the requested information will be processed with the response updating the page as and when it arrives.