开发者

Submit a form and get a JSON response with jQuery

开发者 https://www.devze.com 2023-01-02 05:24 出处:网络
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:

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" />
</for开发者_StackOverflow社区m>

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?


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.


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 :)


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>');
    });
});
  • http://api.jquery.com/jQuery.getJSON/
  • http://api.jquery.com/serialize/
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号