Return from nested function in javascript

I am trying to create a function that uses jquery ajaxfunction to get information from my ajax.php file.

the code:

function ajaxIt(dataLine){ $.ajax({ type: "POST", url: "ajax.php", data: "ajax=true&"+dataLine, success: function(msg){ console.log("[AjaxIt]: "+dataLine+" returned "+msg); return msg; } }); } if(ajaxIt("action=loggedIn")=="1"){ console.log("Logged In"); loggedIn=true; initiate2(); } 

The problem is that I cannot force the success function to fully return to the ajaxIt function. Can someone shed some light on how I could do something like this?

Thanks.

+4
source share
2 answers

You need to call the callback function to process the data like this:

 function ajaxIt(dataLine, cb){ $.ajax({ type: "POST", url: "ajax.php", data: "ajax=true&"+dataLine, success: function(msg){ if($.isFunction(cb)) cb.apply(null, [msg]); } }); } ajaxIt("action=loggedIn", function(data){ if(data === "1"){ console.log("Logged In"); loggedIn=true; initiate2(); } }); 
+9
source

$.ajax is asynchronous. This means that it will return immediately, instead of waiting for the AJAX request to complete and receiving the result from the server. By the time the message arrived from the server, your ajaxIt function ajaxIt already completed its work.

What you should use here is a continuation style. Provide ajaxIt with the continuation: a function that explains what should be done after ajaxIt .

 function ajaxIt(data, continuation) { data.ajax = true; $.post("ajax;php", data, function(msg) { console.log("[AjaxIt]: returned "+msg); continuation(msg); }); } ajaxIt({action:"logged-in"}, function(result) { if (result == "1") { console.log("Logged In"); loggedIn=true; initiate2(); } }); 
+1
source

All Articles