Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I use jQuery to ajaxify a form?

Tags:

jquery

ajax

forms

I'm trying to AJAXIFY a form without using jQuery plugins. What is the process for making this happen. I have my form. What should I set the action to? What should the header script be? Keep in mind that I do not want to use any plugins. I just need a basic algorithm for ajaxifying forms using jquery.

like image 335
wufwufpoof Avatar asked Jan 11 '10 16:01

wufwufpoof


People also ask

How can we submit a form using jQuery?

Forms can be submitted either by clicking an explicit <input type="submit"> , <input type="image"> , or <button type="submit"> , or by pressing Enter when certain form elements have focus.

How can we submit a form without refreshing page using jQuery?

Approach: Create an HTML file & add the jquery library CDN above the javascript code. Create 2 input fields, a submit button, and a span to display the result. Add an onsubmit listener to the form and take a callback with one single parameter.

How can I submit a form without refreshing the page?

Use jQuery's submit event to handle the form submit, add return false; at the end of the submit handle function to prevent the page to reload.


1 Answers

The action should be whatever it would be if you weren't using JavaScript.

NB: The links below all go to the relevant section of the jQuery documentation)

Then you would bind a function to the submit event that serialized the form data and used that to make an Ajax request (probably reading the URI from the action attribute). It would have to prevent the default action for submit events.

I believe jQuery sets an X-Requested-With HTTP header. So you just need to modify your server side process to return different data if that is present (with the right value). This could be as simple as just switching to a different view (if you are using a MVC pattern).

like image 105
Quentin Avatar answered Nov 01 '22 15:11

Quentin