How to get return value from JavaScript function containing jQuery.get ()?

I have a JavaScript method that calls JQuery.get (), and I want to return a value from the itto callle function. Below is the code:

function CheckExistance(userName) {
        $.get(
            "JQueryPage.aspx", { name: userName },
             function(result) {
                 if (result == "1") {
                     value = true;
                 }
                 else if (result == "0") {
                     value = false;
                 }
                 else if (result == "error") {
                     value = false;
                 }
             }
        );                
        return value;
    }

I want return value;to return the value set in the function get()... I know what get()is an asynchronous operation, and I want this solution to resolve?

+3
source share
3 answers

You cannot "return" the value to the called function; because, as you understand, the AJAX call is asynchronous. Instead, you need to effectively delay the execution of the code following the AJAX call; putting this code in a function callback.

, , , AJAX , value.

function CheckExistance(userName, callback) {
        $.get(
            "JQueryPage.aspx", { name: userName },
             function(result) {
                 var value = false;

                 if (result == "1") {
                     value = true;
                 }


                 callback(value);
             }
        );                
    }

, :

function validateUserName() {
    var input = $('someField').val();
    var isUnique = CheckExistance(input);

    if (isUnique) {
       // whatever
    } else {
       alert("This username is already taken");
    };
};

:

function validateUserName() {
    var input = $('someField').val();

    CheckExistance(input, function (isUnique) {
       if (isUnique) {
          // whatever
       } else {
          alert("This username is already taken");
       };
    });
};
+7

,

    function test() {
      return $.ajax({
      url: "/url/" + param,
      type: 'get',
      dataType: 'html',
      async: false
    }).responseText
}
+2

It might work;

function CheckExistance(userName) {
    var value
    $.get(
        "JQueryPage.aspx", { name: userName },
         function(result) {
             if (result == "1") {
                 value = true;
             }
             else if (result == "0") {
                 value = false;
             }
             else if (result == "error") {
                 value = false;
             }
         }
    );
while(value == undefined);
    return value;
}
-4
source

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


All Articles