javascript - Returning the response from an Jquery AJAX call -


this question has answer here:

i have written function, has check whether username has been taken or not. when call function function, , alert it's return value:

 alert(checkusernameavailable('justausername')); 

it says 'undefined'. i've searched high , low, can't find i'm doing wrong. guess should return php-echo in check.php, doesn't. here's function 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 doing wrong?

ajax calls async, means return data after operation has completed. i.e. method checkusernameavailable never returns information (unless tell within method itself). need following:

// fire , forget method checkusernameavailable("username");  // change success function display require success: function(response) {     alert(response);     $("#somediv").html(response);        }, 

the method fires ajax async method posts check.php. when response received, handle response in function associated success callback of $.ajax. can specify function directly success callback well:

// change success point function name success: foo  // create function handle response function foo(response) {    // response } 

edit:

as per op's comment, need change ajax call synchronous, instead of asynchronous (i've never done synchronous call myself, untested):

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

full api listing here.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -