0

I need to rework a website. I currently have following code:

function combinedServerRequestSync(requestParams) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open('POST', 'utility/php/RequestFile.php', false);
    xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xmlHttp.send(requestParams);

    if(xmlHttp.status === 200){
        return xmlHttp.responseText;
    } else{
        return xmlHttp.statusText;
   }
}

the problem with this is, that it freezes the webpage everytime it runs. Is there a solution for this that doesn't evolve rewriting all method calls.

Florian
  • 13
  • 5
  • You can't check status before request completes and the request is asynchronous so you can't return response either from that function. Suggest you use a request library like superagent or axios if you are making multiple requests throughout the app – charlietfl Jan 10 '18 at 13:25
  • Synchronous XMLHTTP requests are being deprecated *because* they block the main thread and using synchronous requests is generally discouraged. I suppose you could put your request in a [web worker](https://developer.mozilla.org/en-US/docs/Web/API/Worker) and that would technically solve your problem, but a webworker is in itself asynchronous. So no, there's no way to do synchronized requests without freezing the page. – Khauri Jan 10 '18 at 13:27
  • The only way to do this is re write how JavaScript is run in the browser. Blocking scripts block and asynchronous api's don't. Using web worker will not block but is probably more complicated than just using asynchronous api's. – HMR Jan 10 '18 at 14:24

0 Answers0