This is not how asynchronicity works.
You get the alert(data)
before return result;
because $.post
works asynchronously. The form
function executes and returns, and then some time later $.post
will have the Ajax response data available and will call the provided callback function passing the data as an argument.
To accomplish what you want you basically have two options:
- You can either use a callback (that will get called once the asynchronous action completes).
- Use promises/deferreds.
Callback version 1:
function form(elem, callback) {
...
$.post(..., function(data) {
data = f(data); // transform data somehow if you have to
callback(data);
});
}
$(document).on(..., function() {
form($(this), function(data) {
// use data
});
});
Callback version 2:
function form(elem, callback) {
...
$.post(..., callback);
}
$(document).on(..., function() {
form($(this), function(data) {
// use data
});
});
Promises version:
function form(elem) {
...
return $.post(...);
}
$(document).on(..., function() {
form($(this))
.done(function(data) {
// use data
})
.fail(function() {
// error
});
});