Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass entire form as data in jQuery Ajax function

Tags:

jquery

ajax

I have a jQuery ajax function and would like to submit an entire form as post data. We are constantly updating the form so it becomes tedious to constantly update the form inputs that should be sent in the request.

like image 307
Brian Avatar asked Jan 07 '10 10:01

Brian


People also ask

What is formData () in jQuery?

The jQuery Ajax formData is a method to provide form values like text, number, images, and files and upload on the URL sever. The jQuery Ajax formData is a function to create a new object and send multiple files using this object.

How can add multiple form data using jQuery AJAX?

For Sending or inserting or saving multiple data in single click then you have to use Jquery and javascript code. By using Jquery or Javascript code you can generate dynamic HTML field in your HTML form. We can generate any dynamic HTML field by using Jquery and append into your form fields.

What is AJAX form submit?

AJAX form submitting allows you to send data in the background, eliminating the need to reload websites to see the updates. This makes the user experience much smoother.


2 Answers

There's a function that does exactly this:

http://api.jquery.com/serialize/

var data = $('form').serialize(); $.post('url', data); 
like image 108
Will Vousden Avatar answered Oct 14 '22 03:10

Will Vousden


serialize() is not a good idea if you want to send a form with post method. For example if you want to pass a file via ajax its not gonna work.

Suppose that we have a form with this id : "myform".

the better solution is to make a FormData and send it:

    let myform = document.getElementById("myform");     let fd = new FormData(myform );     $.ajax({         url: "example.php",         data: fd,         cache: false,         processData: false,         contentType: false,         type: 'POST',         success: function (dataofconfirm) {             // do something with the result         }     }); 
like image 24
M.Arjmandi Avatar answered Oct 14 '22 03:10

M.Arjmandi