I have a js function , after doing some business logic, the javascript function should return some result to another variable.Sample code below
var response="";
function doSomething() {
$.ajax({
url:'action.php',
type: "POST",
data: dataString,
success: function (txtBack) {
if(txtBack==1) {
status=1;
}
});
return status;
}
Here i want to use like
response=doSomething();
I want to assign a return value "status" "var response".But the result is 'undefined'.
JavaScript passes a value from a function back to the code that called it by using the return statement. The value to be returned is specified in the return. That value can be a constant value, a variable, or a calculation where the result of the calculation is returned.
1.1 A regular functionIt is possible to use a function expression and assign it to a regular variable, e.g. const factorial = function(n) {...} .
You can assign a value to a variable using the = operator when you declare it or after the declaration and before accessing it. In the above example, the msg variable is declared first and then assigned a string value in the next statement.
Or just...
var response = (function() { var a; // calculate a return a; })();
In this case, the response variable receives the return value of the function. The function executes immediately.
You can use this construct if you want to populate a variable with a value that needs to be calculated. Note that all calculation happens inside the anonymous function, so you don't pollute the global namespace.
AJAX requests are asynchronous. Your doSomething function is being exectued, the AJAX request is being made but it happens asynchronously; so the remainder of doSomething is executed and the value of status
is undefined when it is returned.
Effectively, your code works as follows:
function doSomething(someargums) { return status; } var response = doSomething();
And then some time later, your AJAX request is completing; but it's already too late
You need to alter your code, and populate the "response" variable in the "success" callback of your AJAX request. You're going to have to delay using the response until the AJAX call has completed.
Where you previously may have had
var response = doSomething(); alert(response);
You should do:
function doSomething() { $.ajax({ url:'action.php', type: "POST", data: dataString, success: function (txtBack) { alert(txtBack); }) }); };
You could simply return a value from the function:
var response = 0;
function doSomething() {
// some code
return 10;
}
response = doSomething();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With