0

I have a function that needs to either return true; or return false; which contains an ajax call that is the method for determining the conditional result based on the response.

My problem is scoping and I'm not sure how to get out of this one. If I setup as a callback, then the return statement lives within the callback function itself and doesn't execute within the main wrapper function.

How should this be setup to execute correctly? Do I need to completely restructure?

function() {

     var response;

     $.ajax({
         dataType: 'jsonp',
         url: 'https://apilayer.net/api/check?access_key=',
         async: false,
         success: function(json) {
             response = json.score;         
         }
     });


     if (response == 1) {
         return false;
     }

 };
Joe
  • 5,955
  • 2
  • 29
  • 42

3 Answers3

1
dataType: 'jsonp',
async: false,

JSONP requests cannot be made syncronously, so async: false is ignored.

If you weren't making a JSONP request, then using async: false would still be a bad idea (the underlying feature it depends on is deprecated for good reason).

This means that you can't do what you want.

The answers to How do I return the response from an asynchronous call? describe strategies for dealing with this.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

First of all, 'async = false' is not supported anymore so call will be async in nature. Now, you have two options:

  1. initialize conditional var i.e. response with some value. So even if ajax response is not received, you will not face any error on if condition.
  2. put conditional statement inside callback.

If your condition is based on ajax response, then ideal way would be to put it inside callback function. Hope it helps!

Kausha Shah
  • 309
  • 3
  • 9
  • "First of all, 'async = false' is not supported anymore" — That's not true. It has never been supported for JSONP requests. It is still supported (but bad practise) on other kinds of requests. – Quentin Mar 07 '19 at 11:29
  • 1
    @Quentin Yes! it was never supported for jsonp. Thanks for the info! – Kausha Shah Mar 07 '19 at 11:33
-2

if you use async false the request will become synchronous and the code will not be executed until the request is completed. this will slow down the browser.

 var response = $.ajax({
         dataType: 'jsonp',
         url: 'https://apilayer.net/api/check?access_key=',
         async: false,
         success: function(json) {
             response = json.score;         
         }
     });
  • They are using `async: false` already but since they are also using `dataType: 'jsonp'` the rest of your answer (including the bit about the request becoming synchronous) isn't true. – Quentin Mar 07 '19 at 11:28