1

So I've been getting this in my console app.js:159 [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/.

I was looking for a way to parse JSON into a url and came across this code block, which seems to be throwing the error.

function readJSON(file) {
  const request = new XMLHttpRequest();
  request.open('GET', file, false);
  request.send(null);
  if (request.status == 200)
  return request.responseText;
};

After a bit of research I came across setting async = true but didn't have any luck with that.

Also, as a side note, my app uses HTML Geolocation and it's not working on GitHub Pages, but works fine locally. Any ideas on that? Thanks

1 Answer 1

2

Toggle false to true. Syntax: XMLHttpRequest.open(method, url, async)

 request.open('GET', file, true);
 request.onload = function() { 
   //response is available as request.response here
}  
5
  • I did try that, and got a Uncaught SyntaxError: Unexpected token u in JSON at position 0 Apr 13, 2018 at 6:29
  • Ah, it's because the request isn't finished yet when your code gets to request.responseText since it is now async. Updated example above.
    – Jeff J
    Apr 13, 2018 at 6:30
  • Depending on how the calling code is structured, you may need to make changes there as well in order to tell the code to wait for the return of this function's data.
    – Jeff J
    Apr 13, 2018 at 6:40
  • Thanks for the answer. Setting it to true does get rid of the console error message. Now I just have to figure out how to make the app run correctly with it set to true. As you said because of the way the calling code is structured. Apr 13, 2018 at 8:02
  • Take a look at Promises or jQuery Deferred implementations depending on your browser support needs. You could also just call the code that executes when this function returns (what happens with the data?) from inside the .onload callback. request.onload = function() { doNextThing(request.response) }
    – Jeff J
    Apr 13, 2018 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.