Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
31
rated 0 times [  35] [ 4]  / answers: 1 / hits: 82555  / 14 Years ago, wed, june 2, 2010, 12:00:00

I expect this is easy, but I'm not finding a simple explanation anywhere of how to do this. I have a standard HTML form like this:



<form name=new_post action=process_form.json method=POST>
<label>Title:</label>
<input id=post_title name=post.title type=text /><br/>

<label>Name:</label><br/>
<input id=post_name name=post.name type=text /><br/>

<label>Content:</label><br/>
<textarea cols=40 id=post_content name=post.content rows=20></textarea>
<input id=new_post_submit type=submit value=Create />
</form>


I'd like to have javascript (using jQuery) submit the form to the form's action (process_form.json), and receive a JSON response from the server. Then I'll have a javascript function that runs in response to the JSON response, like



  function form_success(json) {
alert('Your form submission worked');
// process json response
}


How do I wire up the form submit button to call my form_success method when done? Also it should override the browser's own navigation, since I don't want to leave the page. Or should I move the button out of the form to do that?


More From » jquery

 Answers
56

If you want to get the response in a callback, you can't post the form. Posting the form means that the response is loaded as a page. You have to get the form data from the fields in the form and make an AJAX request.



Example:



$(function(){
$('form[name=new_post]').submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(json) {
alert(json);
}, 'json');
return false;
});
});


Notice that you have to return false from the method that handles the submit event, otherwise the form will be posted also.


[#96604] Monday, May 31, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
piper

Total Points: 734
Total Questions: 93
Total Answers: 112

Location: Burundi
Member since Wed, Apr 6, 2022
2 Years ago
;