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!
$.ajaxis asynchronous. It might take a while to get a response.