javascript - Let code wait untill AJAX request is done -


i have following code check if username exists. uses ajax-request page, page returns either 1 (username exists) or 0 (username doesn't exist).

function checkusername(username,callback){     $.ajax({         url: '/check_username.php',         type: 'post',         data: {username: username},         datatype: 'json',         success : function(data){             switch(data.response){                 case 0:                     callback(true);                 break;                 case 1:                     callback(false);                 break;             }         }     });                  };  var error;  // 'undefined'  checkusername('abc',function(data){     if(data == false){         // username exists         error = true;     }else{         // username not exist         error = false;     }; });  if(error == false){     alert('username not exist'); }else{     alert('username exists'); }; 

problem

the code checks if error = true (there error, ie. username exists) or error = false, code keeps on running. doesn't wait until ajax-request in checkusername done. it's always "username exists" (because error = undefined, , if-else goes else-statement).

question

how can make sure code waits until ajax-request (the checkusername function) done before going further.

i have "partial" solution: when wrap if-else-statement checks error = true/false in settimeout, works. problem is: how many miliseconds? want have fast possible. 500ms? if ajax-response not done then? 1000ms? isn't long?

i think there better solution doing settimeout. have idea?

if(error == false){     alert('username not exist'); }else{     alert('username exists'); }; 

currently above code on top of javascript, being executed whether call ajax or not.so put other function , call after calling checkusername().

function checkusername(username,callback){     $.ajax({         url: '/check_username.php',         type: 'post',         data: {username: username},         datatype: 'json',         success : function(data){             switch(data.response){                 case 0:                     callback(true);                 break;                 case 1:                     callback(false);                 break;             }         }     });                  };  var error;  // 'undefined'  checkusername('abc',function(data){     if(data == false){         // username exists         error = true;     }else{         // username not exist         error = false;     };     alertmsg(); });  function alertmsg(){ if(error == false){     alert('username not exist'); }else{     alert('username exists'); } } 

Comments