JQuery AJAX callback return

I wrote a function that should check if the username was executed or not. Now, when I call a function from another function and warn it, return the value:

  alert (checkusernameavailable ('justausername')); 

he says 'undefined'. I searched high and low, but cannot find what I am doing wrong. I think it should just return php-echo to check.php, but that is not the case. Here is the function I wrote:

  var checkusernameavailable = function (value) {
     $ .ajax ({
       url: "check.php",
       type: "POST",
       async: false,
       cache: false,
       data: "username =" + value + "",

       success: function (response) {
         alert (response);
         return response;        
       },
       error: function () {
         alert ('ajax error');
       }
     });
   } 

What am I doing wrong?

+8
javascript jquery ajax
07 Oct 2018-10-10T00:
source share
1 answer

AJAX calls are asynchronous, which means that they only return data after the operation completes. That is, the checkusernameavailable method never returns any information (unless you specify it inside the method itself). You need to do the following:

 // Just fire and forget the method checkusernameavailable("userName"); // Change the success function to do any display you require success: function(response) { alert(response); $("#SomeDiv").html(response); }, 

The method runs the asynchronous AJAX method, which is sent to check.php. When the answer is received, you then process that response in the function associated with the success $.ajax . You can also specify a function directly for this callback:

 // Change success to point to a function name success: foo // Create a function to handle the response function foo(response) { // Do something with response } 

EDIT:

According to the OP comment, you need to change your AJAX call as synchronous, not asynchronous (I never made a synchronous call like this myself, so it has not been verified):

 var ajaxResponse; $.ajax({ async: false, success : function (response) { ajaxResponse = response; }, // other properties }); return ajaxResponse; 

Full list of APIs here .

+10
Oct 07 2018-10-10T00:
source share



All Articles