views:

125

answers:

3

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?

A: 

Have you tried using .getJSON() and .serialize()?

$('form').submit(function() {
    $.getJSON('ajax/test.json?' + $(this).serialize(), function(data) {
      $('.result').html('<p>' + data.foo + '</p>'
        + '<p>' + data.baz[1] + '</p>');
    });
});
gurun8
+2  A: 

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.

Guffa
+2  A: 

If you need POST request use jQuery.post() passing the fourth argument "json"

$(function(){
  $("form").submit(function(){
    $.post($(this).attr("action"), $(this).serialize(), function(jsonData){
      console.log(jsonData);
    }, "json");
  });
});

Guffa was faster than me :)

Anpher