Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit a form and get a JSON response with jQuery

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?

like image 257
Leopd Avatar asked Jun 02 '10 18:06

Leopd


People also ask

How can we submit a form using jQuery?

jQuery submit() Forms can be submitted either by clicking on the submit button or by pressing the enter button on the keyboard when that certain form elements have focus. When the submit event occurs, the submit() method attaches a function with it to run. It triggers the submit event for selected elements.

How do I get JSON response?

To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.

Can I submit form with GET method?

The form-data can be sent as URL variables (with method="get" ) or as HTTP post transaction (with method="post" ). Notes on GET: Appends form-data into the URL in name/value pairs. The length of a URL is limited (about 3000 characters)


1 Answers

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.

like image 109
Guffa Avatar answered Sep 25 '22 23:09

Guffa