Submit a form and get a JSON response with jQuery

Posted by Leopd on Stack Overflow See other posts from Stack Overflow or by Leopd
Published on 2010-06-02T18:12:29Z Indexed on 2010/06/02 18:24 UTC
Read the original article Hit count: 230

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery