179

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.

paradocslover
  • 2,932
  • 3
  • 18
  • 44
Brian
  • 26,662
  • 52
  • 135
  • 170
  • 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: https://developer.mozilla.org/en-US/docs/Web/API/FormData – james kenny Jan 31 '17 at 12:48

7 Answers7

314

There's a function that does exactly this:

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

var data = $('form').serialize();
$.post('url', data);
Will Vousden
  • 32,488
  • 9
  • 84
  • 95
85

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
        }
    });
Sam
  • 1,424
  • 13
  • 28
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.

nikola
  • 2,241
  • 4
  • 30
  • 42
  • If you are using PHP it is trivial to parse a querystring using parse_url function: http://us3.php.net/manual/en/function.parse-url.php – Lobos Mar 31 '14 at 17:24
  • I know this is old but how do u know which option(s) were selected using this method? – yardpenalty.com Jul 13 '16 at 17:54
19

Use

serialize( )

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

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

rahul
  • 184,426
  • 49
  • 232
  • 263
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' );
patrick
  • 11,519
  • 8
  • 71
  • 80
  • 2
    To extract the url from the "action" attribute of the form use `url: $(this).attr('action'),` instead – rubo77 Jun 25 '18 at 06: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>
-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)
        }
    });
}
rubo77
  • 19,527
  • 31
  • 134
  • 226