3

I see this error: "[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.", on this code:

var request;
if(window.XMLHttpRequest){
    request = new XMLHttpRequest();
}else{
    request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('GET', 'http://www.mywebsite.com', false);
request.send();

What should I replace the instructions with because they are deprecated?

Helpme
  • 113
  • 2
  • 4
  • 11
  • 3
    `false` => `true` – Jaromanda X Jan 15 '18 at 04:50
  • https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests – Brian Jan 15 '18 at 05:03
  • Possible duplicate of [JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."](https://stackoverflow.com/questions/24639335/javascript-console-log-causes-error-synchronous-xmlhttprequest-on-the-main-thr) – Andrew Marshall Nov 04 '18 at 18:26

2 Answers2

7

you just need to change

request.open('GET', 'http://www.mywebsite.com', false);

to

request.open('GET', 'http://www.mywebsite.com', true);

This will make the request operate asynchronously, meaning the code after it is sent will execute immediately instead of waiting for the request to complete. You can then use an event listener to tell the request what code to run when it's complete.

request.onreadystatechange = function () {
    if(request.readyState === XMLHttpRequest.DONE) {
        console.log("Request completed!");
    }
}
EKW
  • 2,059
  • 14
  • 24
1
request.open('GET', 'http://www.mywebsite.com', false)

It means you are creating a synchronous call to the Web service. So not expecting any call back theoratically.

So to continue with above approach make sure the body is also null.

request.send(null);

if (request.status === 200) {
  console.log(request.responseText);
}

The null parameter indicates that no body content is needed for the GET request. Hence the thread won't be blocked.

Hameed Syed
  • 3,939
  • 2
  • 21
  • 31