views:

1323

answers:

5

Hi All,

How do I handle the scenario where I making a synchronous request to the server using XMLHttpRequest and the server is not available?

xmlhttp.open("POST","Page.aspx",false);
xmlhttp.send(null);

Right now this scenario results into a JavaScript error: "The system cannot locate the resource specified"

+2  A: 

Try the timeout property.

xmlHTTP.TimeOut= 2000
fasih.ahmed
I think this will only work for asynchronous requests, in case of synchronous requests. xmllhttprequest.send will block. We will have to use try..catch as pointed out below:
Ngm
A: 

I tried this but it does not to be work:

xmlhttp.open("POST","Page.aspx",false);             
var xmlReqTimeout = setTimeout('showTimeout();',1000);
xmlhttp.send(null);
if(xmlReqTimeout!=null)
{
    clearTimeout(xmlReqTimeout);
}

function showTimeout()
{   
    xmlhttp.abort();
    alert('The application was unable to communicate with the server. Please check your  internet connection');
}

I think the reason is send(with false as parameter) being a synchronous request, will block the execution of the timeout handler 'showTimeout'?

Ngm
A: 

Ok I resolved it by using try...catch around xmlhttprequest.send

:

xmlhttp.open("POST","Page.aspx",false);              
       try
       {
       xmlhttp.send(null);
       }
       catch(e)
       {
            alert('there was a problem communicating with the server');
       }
Ngm
A: 

You don't check for properly returned status. By the code you gave you are doing a GET request. To propelry check the the status of your request, you must create an event handeler for the onreadystatechange event and then inside it check if the readyState propriety is equal 4 and then inside the method if the status is 200.

You can find a detailed explanation here :Ajax Tutorail by Mozilla

  
xmlhttp.onreadystatechange=function()

xmlhttp.open("GET","Page.aspx",false);
{
  if (xmlhttp.readyState==4) 
  {
     if (xmlhttp.satus==200)
     {
       //Ajax handling logic
     }
  }
}
xmlhttp.send(null);



Nikola Stjelja
A: 

So, is there a way to replay the request if the communication with the the server is unreachable?

e.g. replay the request many times until the server is up and responds! Moreover, I want the request to be synchronous (with the async flag = false).

Thanasis Petsas