5

I'm receiving the error in my project trying an Ajax request

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

function getReviews() {
var toReturn = $.ajax({
    url: 'API/reviews.json',
    async: false
}).responseJSON;
return toReturn;
}

I would like to know if there is a different way to write this to not have that error

Jakub
  • 2,367
  • 6
  • 31
  • 82
  • Well... don't set async to false. Use promises or callbacks to handle the response. – Paul Jun 11 '17 at 19:43
  • That's not an error, that's a *warning* message. But yes, it means what is says, don't use `async: false` and rewrite your code to deal with asynchrony. – Bergi Jun 11 '17 at 19:50

1 Answers1

5

Synchronous XMLHttpRequest is very bad because they are blocking entire app while it's waiting for a response from the server so you never should be using them.

To make your request asynchronous remove async option and specify callback instead:

function getReviews(cb) {
  $.ajax({
      url: 'API/reviews.json'
  }).done(cb);
}

getReviews(function(data) {
  // Access your data here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
G07cha
  • 4,009
  • 2
  • 22
  • 39
  • 1
    Instead of taking a callback, better return the promise. – Bergi Jun 11 '17 at 19:50
  • @KonstantinAzizov thank you! Could you please show me your example using my script how it is now so I can understand what I have to modify please: [code](https://pastebin.com/NFTw59rJ) – Jakub Jun 11 '17 at 19:55
  • @Jakub, here is an [updated code](https://pastebin.com/2mRfUKsY). – G07cha Jun 11 '17 at 20:14
  • @Bergi, I agree that promises are better but I wasn't sure which version of jQuery Jakob is using and also for sake of simplicity I've used a callback interface. – G07cha Jun 11 '17 at 20:16
  • @KonstantinAzizov thank you! That helps :) – Jakub Jun 11 '17 at 20:21
  • You're welcome, don't forget to mark the answer as "Correct" if you found this useful so it won't be listed in "Unanswered" section. – G07cha Jun 11 '17 at 20:24