Javascript value changes outside jquery.post -
i have weired bug driving me crazy time now. have following piece of code:
function isloggedin() { var loggedin = false; var requestdata = { action: 'explore-webdesign-is-loggedin', request_url: location.protocol + '//' + location.host + location.pathname, async: false, data: null }; jquery.post(ajaxurl, requestdata, function(data) { var dataobj = json.parse(data); if (dataobj.success === true) { loggedin = true; alert("1.) " + loggedin); } }); alert("2.) " + loggedin); return loggedin; };
javascript spitts out both alerts, fine, first 1 says '1.) true' while second 1 gives me '2.) false'. going on?
ajax requests asynchronous - final alert being executed while ajax in progress - first alert finishes once ajax done (hence why it's in callback).
you don't return
async method trying do, instead pass callback function in executed once ajax done:
function isloggedin(callback) { ... ... jquery.post(ajaxurl, requestdata, function(data) { ... ... if (dataobj.success === true) { loggedin = true; callback(loggedin); } }); }
then call so:
isloggedin(function(data) { if (data) //user logged in });
Comments
Post a Comment