0

I am trying to get the response text from an URL using ajax. The code below works fine if I set the async flag to false but I get a warning from jQuery saying

jquery.min.js:4 Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

Here is the code:

function verifyUser()
{
    var response = $.ajax({type: "GET", url: "/verify/4512h58", async: false}).responseText;
    console.log(response);
}

and if I set the async flag to true like so

var response = $.ajax({type: "GET", url: "/verify/112358", async: true}).responseText;

I get undefined as output. How to solve this?

Igor
  • 60,821
  • 10
  • 100
  • 175
Sapnesh Naik
  • 11,011
  • 7
  • 63
  • 98

2 Answers2

2

This uses something called promises so it needs to look something like this...

var response = $.ajax({
  type: "GET",
  url: "/verify/4512h58"
}).done(function (response) {
  console.log(response);
});

See for more info

Shaun Sweet
  • 669
  • 5
  • 9
1

Use the callback

var response = "";
$.ajax({type: "GET", url: "/verify/112358", async: true})
     .then(function(x){
        response = x.responseText
     });

See also How do I return the response from an asynchronous call?

Community
  • 1
  • 1
Igor
  • 60,821
  • 10
  • 100
  • 175