views:

93

answers:

3

Hello,

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

+5  A: 

You can perform a synchronous request. I only know how to do this with jQuery, though:

$(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!

elusive
this is the best way! However, many people think that JS Frameworks are evil and tend to code everything themselves.
Alex
I have tried to do it with multiple ways using XmlHttpRequest for example, but I haven't find a way so as to stop the execution until I get a respond..
Thanasis Petsas
Alex, that's me! I'm one of them! ;)
Delan Azabani
A: 

For this you can start loader in javascript as soon as page starts loading and then you can close it when request finishes or your dom is ready. What i am trying to say, as page load starts, start a loader . Then page can do multiple synchronous request using ajax , until and unless you didn't get response, do not close close loader. After receiving the desired in response in final call, you can close the loader.

Yogesh
you are off... he is asking about stalling multiple requests.
Alex
Yes, that's exactly what I want to do..
Thanasis Petsas
@Thanasis Petsas : Please check the edited post. Hope this can help you.
Yogesh
@Yogesh: Can you post a simple example please?
Thanasis Petsas
A: 

You can use XMLHttpRequest object to send your request. once you send your request you can readyState property to identify state. readyState will have following different states.

uninitialized - Has not started loading yet loading - Is loading interactive - Has loaded enough and the user can interact with it complete - Fully loaded

ex:

xmlhttp.open("GET","somepage.xml",true);
xmlhttp.onreadystatechange = checkData;
xmlhttp.send(null);

function checkData()
{
    alert(xmlhttp.readyState);
}

hope this will help

Akie
I want the execution of the program to be serial and I don't want to use callbacks. I want if possible to stop the execution of the program at "xmlhttp.send(null);" call and then to continue after the request has finished.
Thanasis Petsas
You can play with readyState property. May be you can put it in while loop and so that it will not go to next line until execution is finished. Also if you can predict execution time, you may use setTimeOut() function. more on this function you can read here. http://www.w3schools.com/jsref/met_win_settimeout.asp
Akie