Reputation: 231
can you help me with this problem? In success:.... I get a result that I need, but ajaxFunction at the end returns ' ' value.
ajaxFunction = function(lastNumber){
var json_result = '';
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
data: '{"first" : "'+lastNumber+'"}',
url: "http://localhost:8080/some_url",
success: function (result) {
console.log("in success: " + result.result);
json_result = result.result;
}
});
console.log("before return " + json_result);
return json_result;
};
Upvotes: 0
Views: 62
Reputation: 1422
always use $.Deferred()
object and return it in your Ajax call.
use .resolve()
to your deferred variable in your .success()
callback of Ajax call.
Call your method and check with .done
method of your deferred function.
Upvotes: 0
Reputation: 10851
The problem is that your result is returned, and then the ajax called is executed async.
Here's an example for an alternative, by using Deferred.
return value from nested function in jquery
function test(){
var def = new $.Deferred();
$.ajax({
url: 'test',
success: function(data) {
// Do some minor logic to determine if server response was success.
console.log('success in callback');
if(data == true){
def.resolve(true);
}
else{
def.reject();
// or possibly def.resolve(true) depending what you're looking for.
}
},
error:function(){
console.log('error in callback');
def.reject();
}
});
return def;
}
EDIT: Example for your case:
var ajaxFunction = function(lastNumber){
var def = new $.Deferred();
$.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
data: '{"first" : "'+lastNumber+'"}',
url: "http://example.com",
success: function (result) {
console.log("in success: " + result.result);
def.resolve(result.result);
},
error: function(){
def.reject();
}
});
return def;
};
var testMethod = function(){
var result = ajaxFunction('some number');
result.done(function(result){
alert(result);
console.log('done in deferred');
// Do something when everything went well.
}).fail(function(){
alert('error');
console.log('error in deferred');
// Do something when something went bad.
});
}
testMethod();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1
Reputation: 1356
You can put this and try
ajaxFunction = function(lastNumber){
var json_result = '';
$.ajax({
async: false,
type: "POST",
contentType: "application/json",
dataType: "json",
data: '{"first" : "'+lastNumber+'"}',
url: "http://localhost:8080/some_url",
success: function (result) {
console.log("in success: " + result.result);
json_result = result.result;
}
});
console.log("before return " + json_result);
return json_result;
};
It will make the call synchronous as you are setting async to false, which is by default true.
If not working with this one, you can make use of either call back or promise(works and returns like synchronous calls).
Upvotes: 0