ajax - JavaScript callback function is not working in my case -


i have function return ajax response , use on function. here code:

function updateloanapproval(answer){     var password = document.getelementbyid("password").value;     var usid;      getexistingid(function(success){         if (success === 0){             var usid = "no id available";         } else {             var usid = success; //to returning value         }     });      alert(usid); 

and here code getexistingid()

function getexistingid(){     var url =  "../../library/functions.php?action=getid";     var uid;     http.onreadystatechange = function(){         if (http.status == 200 && (http.readystate === 4)){             uid = http.responsetext;             if (uid == "no id"){                 callback(0);             } else {                 callback(id);             }         }     }      http.open("get",url,true);     http.send(); } 

as test code, don't have problem query or php code not include here, why usid return undefined?

see carefully, missing callback parameter in getediistingid() function. following:

function getexistingid(callback){ var url =  "../../library/functions.php?action=getid"; var uid; http.onreadystatechange = function(){     if (http.status == 200 && (http.readystate === 4)){         uid = http.responsetext;         if (uid == "no id"){             callback(0);         } else {             callback(id);         }     } }  http.open("get",url,true); http.send(); 

}

and put alert inside callback method.

function updateloanapproval(answer){     var password = document.getelementbyid("password").value;     var usid;      getexistingid(function(success){         if (success === 0){             var usid = "no id available";         } else {             var usid = success; //to returning value         }         alert(usid);     }); 

a method need usid:

function domytaskthatneedusid(usid) {     // something. } 

and call method following:

function updateloanapproval(answer){     var password = document.getelementbyid("password").value;     var usid;      getexistingid(function(success){         if (success === 0){             var usid = "no id available";         } else {             var usid = success; //to returning value         }          // calling method need usid.         domytasktaskthatneedusid(usid);     }); 

Comments