Reputation: 6099
I have written a function which is used when a form is posted to post data to a URL. However I'm not sure how I can return the result within the function so that I can check when the function is called, what the response is.
Basically I want the response
value in the function to be returned so that I can access it.
/**
* Submit (POST) the Form via Ajax
*
* @param form
* @param action
* @param data
* @param container
*/
function postForm(form,action,method,container){
$.ajax({
type: 'post',
dataType: 'json',
url: action,
data: form.serialize(),
error: function(xhr, status, error) {
// Display errors
var err = JSON.parse(xhr.responseText);
var errMsg = '';
$.each(err, function(name, val) {
errMsg += val + '<br>';
});
new PNotify({
title: "Error!",
text: errMsg,
type: 'error',
animate_speed: 'fast'
});
},
success: function (response) {
handleResponse(method, container, response);
return response;
}
});
}
I want to use it like this:
var result = postForm(
form,
form.attr('action'),
form.attr('data-method'),
$(form.attr('data-container'))
);
alert(result);
At the moment, the var result
outputs undefined
.
Please help!
Upvotes: 0
Views: 920
Reputation: 1964
Your function should return a promise object:
function postForm(form,action,method,container){
var promise = $.ajax({
type: 'post',
dataType: 'json',
url: action,
data: form.serialize(),
error: function(xhr, status, error) {
// Display errors
var err = JSON.parse(xhr.responseText);
var errMsg = '';
$.each(err, function(name, val) {
errMsg += val + '<br>';
});
new PNotify({
title: "Error!",
text: errMsg,
type: 'error',
animate_speed: 'fast'
});
},
success: function (response) {
handleResponse(method, container, response);
return response;
}
});
return promise;
}
now your caller will reference the promise of the ajax request. so now you do:
var promise = PostForm(...);
promise.done(function(data) {
do your thing
})
You should read this:How do I return the response from an asynchronous call?
Upvotes: 1
Reputation: 68
You can handle the situation like this:
success: function (response) {
handleResponse(method, container, response);
//return response;
doSomething(response);
}
and then:
function doSomething(response) {
alert(response);
}
maybe you want to make the call sync (not suggested) by specifying:
$.ajax({
type: 'post',
dataType: 'json',
url: action,
async: false
...
Upvotes: 0