Facilitate callback return valueSuccess for Caller function return value

I have a javascript function that calls a generic function to call ajax to a server. I need to get the result (true / false) from the ajax callback function, but the result I get is always "undefined".

A super simplified version of a common function without my logic would be:

function CallServer(urlController) { $.ajax({ type: "POST", url: urlController, async: false, data: $("form").serialize(), success: function(result) { if (someLogic) return true; else return false; }, error: function(errorThrown) { return false; } }); } 

And the function calling it will look something like this:

 function Next() { var result = CallServer("/Signum/TrySave"); if (result == true) { document.forms[0].submit(); } } 

The variable "result" is always "undefined", and debugging it, I see that the line "return true" of the callback function is executed.

Any ideas why this is happening? How could I call the return value from the CallServer callback?

thanks

+6
javascript jquery ajax
source share
3 answers

Just found how to do it :) Declaring a variable and updating it accordingly from the callback function. Subsequently, I can return this variable. I am posting code for future readers:

 function CallServer(urlController) { var returnValue = false; $.ajax({ type: "POST", url: urlController, async: false, data: $("form").serialize(), success: function(result) { if (someLogic){ returnValue = true; return; } }, error: function(errorThrown) { alert("Error occured: " + errorThrown); } }); return returnValue; } 
0
source share

Just in case, you want to go asynchronously (this is the best solution, because it will not block your browser when executing the request), here is the code:

 function CallServer(urlController, callback) { $.ajax({ type: "POST", url: urlController, async: true, data: $("form").serialize(), success: function(result) { var ret = ( someLogic ); callback(ret); }, error: function(errorThrown) { return false; } }); } function Next() { CallServer("/Signum/TrySave", function(result) { if (result == true) { document.forms[0].submit(); } }); } 
+15
source share

I usually put any code that succeeds inside the callback function itself. I don't think CallServer() really gets the return values ​​from the callbacks themselves.

Try something like:

 function CallServer(urlController) { $.ajax({ type: "POST", url: urlController, async: false, data: $("form").serialize(), success: function(result) { if (someLogic) document.forms[0].submit(); else // do something else }, error: function(errorThrown) { // handle error } }); } 

Edit: I am not very familiar with jQuery, so I can be completely wrong (I base this on the behavior of other frameworks such as YUI and AJAX calls made without any frameworks). If so, just run this answer and leave a comment and I will delete this answer.

0
source share

All Articles