182

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.

1
  • Moh is correct about FormData() and images. But to clarify further. It is that serialise only works on strings (not binary data). the FormData() function works with forms that have the encoding type set to "multipart/form-data". Details here: developer.mozilla.org/en-US/docs/Web/API/FormData Jan 31, 2017 at 12:48

8 Answers 8

317

There's a function that does exactly this:

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

var data = $('form').serialize();
$.post('url', data);
6
  • 4
    $.post also can call a function on success. $.post('url', data, function() { .... });
    – slm
    Jul 6, 2012 at 16:43
  • 26
    note: the form fields must have the name attribute set, using only ID does not work as documented and as I found out first hand. Jan 26, 2013 at 22:05
  • what is I need some input with the same name ? I mean, like having them in rows ? how can I send that in an array or something ? Feb 9, 2015 at 18:02
  • 2
    @FranciscoCorralesMorales name your inputs like this way: person[0].firstName person[0].lastName person[1].firstName person[1].lastName
    – ahmehri
    May 11, 2015 at 8:28
  • @ahmehri, so is this a valid HTML <input name="person[1].lastName"> ? May 11, 2015 at 16:01
87

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 (response) {
            // do something with the result
        }
    });
6
  • 1
    Yes it's supported by updated browsers but by using serialized you can only pass strings.
    – Sam
    Aug 19, 2015 at 11:00
  • 4
    Maybe you should mention that in your answer
    – toesslab
    Aug 19, 2015 at 11:05
  • Thank you, for both var, in 2016!
    – Sylar
    Jun 26, 2016 at 10:03
  • 1
    you beauty! worked like charm (form data + file upload)
    – saibbyweb
    Mar 24, 2018 at 17:29
  • 2
    can't emphasize this enough! tried form.serialize() but it just didn't work for file upload. new FormData(this) worked nicely Apr 9, 2018 at 23:23
27

In general use serialize() on the form element.

Please be mindful that multiple <select> options are serialized under the same key, e.g.

<select id="foo" name="foo" multiple="multiple">
    <option value="1">one</option>
    <option value="2">two</option>
    <option value="3">three</option>
</select>

will result in a query string that includes multiple occurences of the same query parameter:

[path]?foo=1&foo=2&foo=3&someotherparams...

which may not be what you want in the backend.

I use this JS code to reduce multiple parameters to a comma-separated single key (shamelessly copied from a commenter's response in a thread over at John Resig's place):

function compress(data) {
    data = data.replace(/([^&=]+=)([^&]*)(.*?)&\1([^&]*)/g, "$1$2,$4$3");
    return /([^&=]+=).*?&\1/.test(data) ? compress(data) : data;
}

which turns the above into:

[path]?foo=1,2,3&someotherparams...

In your JS code you'd call it like this:

var inputs = compress($("#your-form").serialize());

Hope that helps.

2
20

Use

serialize( )

var str = $("form").serialize();

Serialize a form to a query string, that could be sent to a server in an Ajax request.

5

A good jQuery option to do this is through FormData. This method is also suited when sending files through a form!

<form id='test' method='post' enctype='multipart/form-data'>
   <input type='text' name='testinput' id='testinput'>
   <button type='submit'>submit</button>
</form>

Your send function in jQuery would look like this:

$( 'form#test' ).submit( function(){
   var data = new FormData( $( 'form#test' )[ 0 ] );

   $.ajax( {
      processData: false,
      contentType: false,

      data: data,
      dataType: 'json',
      type: $( this ).attr( 'method' );
      url: 'yourapi.php',
      success: function( feedback ){
         console.log( "the feedback from your API: " + feedback );
      }
});

to add data to your form you can either use a hidden input in your form, or you add it on the fly:

var data = new FormData( $( 'form#test' )[ 0 ] );
data.append( 'command', 'value_for_command' );
1
  • 2
    To extract the url from the "action" attribute of the form use url: $(this).attr('action'), instead
    – rubo77
    Jun 25, 2018 at 6:40
0

You just have to post the data. and Using jquery ajax function set parameters. Here is an example.

<script>
        $(function () {

            $('form').on('submit', function (e) {

                e.preventDefault();

                $.ajax({
                    type: 'post',
                    url: 'your_complete url',
                    data: $('form').serialize(),
                    success: function (response) {
                        //$('form')[0].reset();
                       // $("#feedback").text(response);
                        if(response=="True") {
                            $('form')[0].reset();
                            $("#feedback").text("Your information has been stored.");
                        }
                        else
                            $("#feedback").text(" Some Error has occured Errror !!! ID duplicate");
                    }
                });

            });

        });
    </script>
0

Best way to Pass All Inputs to Form Data Object ( text , hidden , radio And Text Area) :)

function pass_all_inputs_form_data(form_id) {
    var form_data = new FormData();
    var inputs = $('#' + form_id)[0].getElementsByTagName("input")
    for (i = 0; i < inputs.length; i++) {
        if (inputs[i].type == 'radio') {
            if (inputs[i].checked == true) {
            }
        } else {
            form_data.append(inputs[i].id, inputs[i].value);
        }
    }
    var textareas = $('#' + form_id)[0].getElementsByTagName("textarea")
    for (i = 0; i < textareas.length; i++) {
        form_data.append(textareas[i].id, $('#' + textareas[i].id).val());
    }
    return form_data;
}
-1

The other solutions didn't work for me. Maybe the old DOCTYPE in the project I am working on prevents HTML5 options.

My solution:

<form id="form_1" action="result.php" method="post"
 onsubmit="sendForm(this.id);return false">
    <input type="hidden" name="something" value="1">
</form>

js:

function sendForm(form_id){
    var form = $('#'+form_id);
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: $(form).serialize(),
        success: function(result) {
            console.log(result)
        }
    });
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.