Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JQuery $.get to determine return value?

Tags:

jquery

ajax

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 any easy way to do this?

like image 391
William Avatar asked Dec 02 '25 08:12

William


1 Answers

You can't do it that way. .get() like any other ajax method runs asynchronously (unless you explicitly set it to run synchronously, which is not very recommendable). So the best thing you can do probably is to pass in 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
});
like image 72
jAndy Avatar answered Dec 03 '25 21:12

jAndy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!