benchpresser benchpresser - 16 days ago 6
Ajax Question

Sending ajax request and receiving response (synchronised)

I am sending ajax request and handle the response in my js/html application. The device is Windows Mobile CE, there is no jquery support and the device browser (IE) does not support eventhandlers, so i can not use asynch calls. Anyway, my problem is, before sending the event, i want to display a please wait message and upon receiving response i want to hide it again.

function sendRequest() {
// make please wait visible
document.getElementById("pleasewait").style.display = "block";
console.log("pleasewait visible.");

var XHR = new XMLHttpRequest();
// synch call

XHR.send(sendData);

// suppose it takes 20-30 seconds
console.log("response received :" + XHR.responseText);

XHR.open('POST', 'url', false);

// make please wait hidden
document.getElementById("pleasewait").style.display = "none";
}


But, when I run it, the pleasewait element is made visible when we receive response (not before sending) and becomes immediatelty hidden again even if the process takes for example 20-30 seconds. The console messages are displayed in the correct order, but the please wait element is not updated correctly. I tried some setTimeouts but no desired result. I can not add some jsfiddle because it is hard to implement ajax request handler on th remote.

Answer

Browsers will freeze when doing synchronous ajax request hence the synchronous request prevents the display re-flow!

Only solution I will suggest is to use setTimeout with 0 duration!

function sendRequest() {
  document.getElementById("pleasewait").style.display = "block";
  setTimeout(function() {
    var XHR = new XMLHttpRequest();
    XHR.send(sendData);
    console.log("response received :" + XHR.responseText);
    XHR.open('POST', 'url', false);
    document.getElementById("pleasewait").style.display = "none";
  }, 0);
}

Note: Here is a some relevant information!