jquery ajax Function undefined -
returning response function every time end undefined function!!
var result = checkusers();(result undefined) function checkuser() { var empname = $("#txtname").val(); $.ajax({ type: "post", url: location.pathname + "/userexist", data: "{name:'" + empname + "'}", contenttype: "application/json; charset=utf-8", datatype: "jsondata", async: "true", success: function (response) { console.log(response.d); var obj = eval('(' + response.d + ')'); return obj; }, error: function (response) { alert(response.status + ' ' + response.statustext); } }); } i calling function
var result = checkuser(); if(result== false){ //do } else{ //do } i have struggling past 1 day!! read in section because of 'ajax asynchronous' . how handle it??
you're better off passing callback function checkuser
function checkuser(callback) { var empname = $("#txtname").val(); $.ajax({ type: "post", url: location.pathname + "/userexist", data: "{name:'" + empname + "'}", contenttype: "application/json; charset=utf-8", datatype: "jsondata", async: "true", success: function (response) { console.log(response.d); var obj = eval('(' + response.d + ')'); callback(obj); }, error: function (response) { alert(response.status + ' ' + response.statustext); callback(null); } }); } you call function so
checkuser(function (res) { if (res === null) { //false } else { //true } });
Comments
Post a Comment