0

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!

2
  • $.ajax is asynchronous. It might take a while to get a response. Commented Nov 26, 2015 at 15:49
  • you need to return a promise from your PostForm function. you have to understand this concept before you move on: api.jquery.com/promise Commented Nov 26, 2015 at 15:57

2 Answers 2

1

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?

Sign up to request clarification or add additional context in comments.

Comments

0

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 ... 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.