Reputation: 613
I have a jquery $.post function lik so:
$.post('/test',json_data, function(data) {
result=data
});
this function is actually being used in an validation...So it the return value(data) contains true or false. But this value is not being stored in the variable 'result'. I understand that this is because post makes an asynchronous call and hence it does'nt wait for the response. What I want to ask is, is there some workaround for this? or can this call be made synchronous somehow??
Upvotes: 1
Views: 2883
Reputation: 340713
This is considered a bad practice but there is an async
parameter in $.ajax()
that you can set to false
and wait synchronously for a result:
var result;
$.ajax({
type: 'POST',
url: '/test',
data: json_data,
async: false,
success: function(data) {
result=data;
},
dataType: 'application/json'
});
//result available here
A more idiomatic, although slightly less convenient in this case, would be to take advantage of callbacks:
function validate(okCallback, errorCallback) {
$.post('/test',json_data, function(data) {
if(data) {
okCallback();
} else {
errorCallback();
}
});
}
validate(
function() {
//proceed
},
function() {
//display validation error
}
}
Upvotes: 4
Reputation: 1475
Check for validity inside the callback
$.post('/test',json_data, function(data) {
var result=data;
if(result === true) {
// do some ok processing...
} else {
// do not ok processing...
}
});
Upvotes: 2