Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force a program to wait until an HTTP request is finished in JavaScript?

Is there a way in JavaScript to send an HTTP request to an HTTP server and wait until the server responds with a reply? I want my program to wait until the server replies and not to execute any other command that is after this request. If the HTTP server is down I want the HTTP request to be repeated after a timeout until the server replies, and then the execution of the program can continue normally.

Any ideas?

Thank you in advance, Thanasis

like image 909
Thanasis Petsas Avatar asked Sep 21 '10 12:09

Thanasis Petsas


People also ask

How do you wait for a method to end in JavaScript?

Use async/await to Wait for a Function to Finish Before Continuing Execution. Another way to wait for a function to execute before continuing the execution in the asynchronous environment in JavaScript is to use async/wait .

How do I wait for API response in node JS?

I would use async/await. If you run your whole main program in an async function that you call immediately, you can put await before any function that returns a Promise .


2 Answers

There is a 3rd parameter to XmlHttpRequest's open(), which aims to indicate that you want the request to by asynchronous (and so handle the response through an onreadystatechange handler).

So if you want it to be synchronous (i.e. wait for the answer), just specify false for this 3rd argument. You may also want to set a limited timeout property for your request in this case, as it would block the page until reception.

Here is an all-in-one sample function for both sync and async:

function httpRequest(address, reqType, asyncProc) {   var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");   if (asyncProc) {      req.onreadystatechange = function() {        if (this.readyState == 4) {         asyncProc(this);       }      };   } else {      req.timeout = 4000;  // Reduce default 2mn-like timeout to 4 s if synchronous   }   req.open(reqType, address, !(!asyncProc));   req.send();   return req; } 

which you could call this way:

var req = httpRequest("http://example.com/aPageToTestForExistence.html", "HEAD");  // In this example you don't want to GET the full page contents alert(req.status == 200 ? "found!" : "failed");  // We didn't provided an async proc so this will be executed after request completion only 
like image 176
Javarome Avatar answered Sep 18 '22 06:09

Javarome


You can perform a synchronous request. jQuery example:

$(function() {     $.ajax({        async: false,        // other parameters     }); }); 

You should take a look at jQuery's AJAX API. I highly recommend using a framework like jQuery for this stuff. Manually doing cross-browser ajax is a real pain!

like image 25
jwueller Avatar answered Sep 19 '22 06:09

jwueller