Using jquery $ .get to determine return value?

I am trying to determine the return value of a function based on the result of a jQuery $ .get request:

    function checkResults(value) {
       $.get("checkDuplicates.php", {
          value: value
       }, function(data) {
          if(data == "0") {
             //I want the "checkResults" function to return true if this is true
          } else {
             //I want the "checkResults" function to return false otherwise
          }
       });
   }

Is there an easy way to do this?

+3
source share
2 answers

You cannot do that. .get(), like any other ajax method, it runs asynchronously (unless you explicitly ran it synchronously, which is not highly recommended). So the best thing you can do is pass a callback.

function checkResults(value, callback) {
   $.get("checkDuplicates.php", {
      value: value
   }, function(data) {
      if(data == "0") {
         if(typeof callback === 'function')
            callback.apply(this, [data]);
      } else {
         //I want the "checkResults" function to return false otherwise
      }
   }
}

checkResults(55, function(data) {
   // do something
});
+6
source

No, you will need to make a callback that will be executed after the request completes. You can pass the return value to the callback. The callback will have to act on the result.

+3
source

Source: https://habr.com/ru/post/1784625/


All Articles