jQuery API

.serialize()

.serialize() Returns: String

Description: Encode a set of form elements as a string for submission.

  • version added: 1.0.serialize()

The .serialize() method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements. The form elements can be of several types:

<form>
  <div><input type="text" name="a" value="1" id="a" /></div>
  <div><input type="text" name="b" value="2" id="b" /></div>
  <div><input type="hidden" name="c" value="3" id="c" /></div>
  <div>
    <textarea name="d" rows="8" cols="40">4</textarea>
  </div>
  <div><select name="e">
    <option value="5" selected="selected">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
  </select></div>
  <div>
    <input type="checkbox" name="f" value="8" id="f" />
  </div>
  <div>
    <input type="submit" name="g" value="Submit" id="g" />
  </div>
</form>

The .serialize() method can act on a jQuery object that has selected individual form elements, such as <input>, <textarea>, and <select>. However, it is typically easier to select the <form> tag itself for serialization:

$('form').submit(function() {
  alert($(this).serialize());
  return false;
});

This produces a standard-looking query string:

a=1&b=2&c=3&d=4&e=5

Warning: selecting both the form and its children will cause duplicates in the serialized string.

Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.

Example:

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

<!DOCTYPE html>
<html>
<head>
  <style>
  body, select { font-size:12px; }
  form { margin:5px; }
  p { color:red; margin:5px; font-size:14px; }
  b { color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  

<form>
    <select name="single">
      <option>Single</option>
      <option>Single2</option>
    </select>

<br />
    <select name="multiple" multiple="multiple">
      <option selected="selected">Multiple</option>
      <option>Multiple2</option>

      <option selected="selected">Multiple3</option>
    </select>
<br/>
    <input type="checkbox" name="check" value="check1" id="ch1"/>

    <label for="ch1">check1</label>

    <input type="checkbox" name="check" value="check2" checked="checked" id="ch2"/>

    <label for="ch2">check2</label>
<br />
    <input type="radio" name="radio" value="radio1" checked="checked" id="r1"/>

    <label for="r1">radio1</label>
    <input type="radio" name="radio" value="radio2" id="r2"/>

    <label for="r2">radio2</label>
  </form>
  <p><tt id="results"></tt></p>
<script>
    function showValues() {
      var str = $("form").serialize();
      $("#results").text(str);
    }
    $(":checkbox, :radio").click(showValues);
    $("select").change(showValues);
    showValues();
</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .serialize() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .serialize()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • http://twitter.com/kcssm Sanam Maharjan

    Happy Birthday jQuery.
    Ever since I have come across this, it feels like javascript is in my finger tips. “Write less, do more” has has been the motto of my programming ever since.
    Lately I have been trying to use the .serialize() method to post the form elements through ajax. But I could not send the element value using .serialize(). I googled but in vain as I could not find any reference about it. Now release of jQuery1.4 raised some hope and started looking for .serialize(), but nothing was mentioned about the here either. Is it that I am not looking at a correct place or it does not support it? Thanks for help in advance.

  • http://twitter.com/skleinei S. Kleineikenscheidt

    How would you expect the contents of the element be serialized? This method will probably not help you. I have been using the form plugin for uploading files (see http://jquery.malsup.com/form/).

  • Anonymous

    File uploads cannot be handled in Ajax. The best you can do is to upload behind the scenes, with a full page refresh submission in a hidden iframe. As far as I know, this is a limitation imposed by the security restrictions on javascript, and I don’t believe there’s anything Javascript libraries such as JQuery can do about it. Some alternatives include Flash (??) and Java. You could use Active-X controls too I think, but why on earth would you want to do a thing like that ?

  • SGJack

    serialize() doesn’t include input type=submit name+value… seems pointless to serialize only part of the form data IMO – If nothing else maybe this post will save some1 some time. -SGJ

  • http://sumeetjain.com Sumeet Jain

    What is the best practice for serializing a form to JSON?

  • http://sumeetjain.com Sumeet Jain

    One method I achieved was to use jQuery’s serializeArray() and then JSON.stringify() (requires http://json.org/json2.js). So:

    myJSONdata = JSON.stringify($(“#formID”).serializeArray());

    NOTE: I ended up not needing/using JSON, so I didn’t test this method thoroughly. It seemed to work at first glance, though.

  • http://www.preprod-sbeirnaert.fr/ Sébastien BEIRNAERT

    Yes you can both upload a file and make an ajax request using file’s informations (filename, size …) without refreshing the browser. This is about mixing iframes and ajax techniques. You can execute a form in an iframe ().
    Here is a link : http://www.atwebresults.com/php_ajax_image_upload/
    If you can understand french, this is brillant : http://www.xorax.info/blog/programmation/114-input-file-iframe.html#127-ajax-upload-input-file.html/#

  • http://www.mojoportal.com Joe Audette

    I think that serializing forms to query string params is not really a good idea because the benefit of form fields vs query string params is that form fields are not posted in the query string and if ssl is used the data posted is secure because it is encrypted whereas query string params are not encrypted even if ssl is used. So it seems we are exposing data with this technique when we would like to keep it private. I wonder how many people are mistakenly using this technique on pages protected with ssl.

  • Anonymous

    Submit name+value isn’t submitted, if it’s not pressed – just like in simple upload (i mean not ajax).. You can have 10 submit buttons, but only the name and value from the pressed one will be sent to server..

  • Anonymous

    You can use it with POST queries – the data is still encoded in the same way, even if you don’t see it in the address bar ;)
    For example,
    $.post(“test.php”, $(“#testform”).serialize());

  • stephenrs

    this is not true. serialize won’t pass the name/value of the submit button that was pressed (only the other fields in the form). this is a problem if you have multiple submit buttons on the same form which are supposed to do different things….

  • http://twitter.com/freelance_jobs Freelance Jobs

    The event is not connected to serialization of the form. If you want to add the submit button chosen, add it programatically with the event handler.

    Eg:

    $(‘#submit1′).click(function() { $(‘#myform’).serialize() + ‘submit1=submit’; });

  • http://sameprecision.org/ same

    Over SSL, the entire http request is encrypted, including the request header.
    Granted, the query string might show up in the server log…

  • http://www.mojoportal.com Joe Audette

    There are other ways it can leak data too but logging sensitive data into clear text in the server log is bad enough. A mistake like that could cost one his job.
    http://stackoverflow.com/questions/323200/is-a-https-query-string-secure

  • David

    You don’t lose the ability to use Request.Form[key]

  • silver

    I don’t know about “best practice”, but see the jQuery.serializeArray() function for a start you off

  • http://twitter.com/EspacioDarkBlue DarkBlue Marketing

    Serialize works fine for GET, but when you POST spanish or UTF-8 characters the server doesn’t get it well… a .plainSerialize() or .serializeNoEncoding() will be very appreciated to keep the “Write less do more”. Best Regards!

  • http://www.mojoportal.com Joe Audette

    I said “unless you submit an actual form what you get is a request body that looks like a query string, it has no html form” so clearly I am not submitting a form. Yes of course if you post the form like in the example it works and you can use Request.Form[key]. But in ASP.NET WebForms we have only 1 form on the page and it contains all form fields for the entire page. Often I want to post just a couple of fields and NOT the whole heavy form like this:
    var ratingData = “cid=” + this._contentId + “&r=” + this._ratingValue;

    $.ajax({
    type: “POST”,
    async: false,
    processData: false,
    url: this._jsonUrl,
    data: ratingData,
    contentType: “text/javascript”,
    dataType: “json”,
    success: function(data) {
    result = data.avg;
    votes = data.votes;

    }
    });

    In this case there is no form posted and you cannot use Request.Form[key] to retrieve the posted values. A less experienced developer might just change it to GET and then could use Request.QueryString[key]. In my example above it is using post and the request body looks like a query string but has no form.

    So yes it works if you serialize a form and post the form but if you just serialize a few fields and not the whole form then you have no form.
    Possibly I could dynamically create a small form around the few fields post it then remove it but it would be easier if I could just create a string representation of a form and its fields and post that.
    So basically in ASP.NET WebForms we have this single form per page limit and I find I often do not want to submit the form because it would be heavy compared to posting the few small values I want to post.

  • David

    I see your point with the stubborn asp.net webforms’ one form/page restriction. Please just admit you were wrong when you said “it loses the convenience of being able to get at the params with Request.Form[key]…”.

    Also: JQuery’s ajax POST request is almost identical to a traditional form POST. The only part that is missing is “Content-Type: {type} nContent-Length: {n} nn.” So where’s the problem?

  • Anonymous

    don’t forget to wait the document is ready before calling the submit function. And to put this script BEFORE the form.

    $(document).ready(function() {
    $(‘#formRecherche’).submit(function() {
    alert($(‘#myForm’).serialize());
    });
    });

  • stephen

    If you were responding to my post about info not being sent, first thanks. Yes, we did try what you suggested just to make sure. However, the problem seems to be IE’s limit on URL strings. We tried the POST feature for jquery Ajax, but it seems that feature also serialize the info. Am I mistaken? Any way to post as we do with a regular HTML form accept just in an unobtrusive ajax/jquery way?

  • meng

    is it possible to automatically assign serialized data to a form ? like $(‘#formId’).unserialize(serializedData); ?

  • Gordon Johnson

    Noted in the description is that you can serialize anything, but only the form is shown in the example.

    Perhaps I'm a little off but if all the inputs are at the same level as the submit button:

    $(“#mySubmitButton”).siblings().serialize();

    works for me. I have a bad setup where code creates multiple forms all having the same name and id

  • tom

    The serialize function doesn’t care if submit is pressed or not, it never includes it. This doesn’t seem to make sense if you bind the ajax call to the form’s ‘submit’ event and still use the submit button as normal.

  • shane

    An issue I see with serialize is you lose apostrophe values, for example I have a select menu with options that have values with apostrophe in them, but if you try to .post with serialize(), the value will be cut off, is there a way around this?

  • Amaranthe

    Is it only apostrophes? Are you able to use double quotes, ampersands, and other characters that would typically be converted to hex for querystring use?

    I’m new to JQuery and know that all my own javascript library functions had to handle generating the querystring with caution to ensure the data would work properly.

  • Amaranthe

    Is it only apostrophes? Are you able to use double quotes, ampersands, and other characters that would typically be converted to hex for querystring use?

    I’m new to JQuery and know that all my own javascript library functions had to handle generating the querystring with caution to ensure the data would work properly.

  • Alex

    Correction: To the best of my testing ability, I believe that .serialize does not process all successful controls, as defined at the given W3C link. The value of the clicked submit button does not appear to be processed, or, if it is processed, there is no way to access it.

  • Steven Petryk

    Am I the only one who's having issues with hidden input values not being retrieved? If I alert the serialized form it shows the name but no value.

  • khairil

    I use serialize() in the ajax call. this might give you idea somewhere?
    <form id=”myform” action=”backend.php”>

    <input id=”hiddenfield” name=”hiddenfield” type=”hidden” value=”hidden value”/>
    <input id=”submit” type=”submit” value=”enter” onclick=”submitMe();return false;” />
    </form>
    <div id=”result”></div>

    function submitMe() {
    $.post($(“#myform”).attr('action'), $(“#myform”).serialize(), function(data) {
    $(“#result”).html(“Return result: ” + data);
    }
    }
    in backend.php
    <?php
    echo $_POST['hiddenfield'];
    /* end here */

  • oscar974

    Hello, maybe someone could get interested in my problem…
    IE add %0A %0D %0D… all around my parameters with the serialize() function ; I know these are HTML codes.
    It works well with Firefox though.
    Any idea?

  • http://www.acousticwebdesign.net Mitchell Hall

    Same problem here. Hidden fields are not serialized. Or a better description would be that the value of hidden fields aren't being serialized. The query string contains the name of the hidden field, but no value.

  • gobanic

    can those serialize elements be <input type=”file”>??

  • Bram

    You could try:
    decodeURIComponent($(“form”).serialize())

  • outofbounds.gr

    .serialize() serializes x,y coordinates if the submit “button” is an image!
    any way to avoid that? ignoring the x,y values after the post , is kind of a solution

  • http://twitter.com/abyss__ Muneeb Shahid

    hi
    hidden fields are being serialized in my form. probably new version of jquery has been released since your post

  • nichole

    From above paragraph,–>”Data from file select elements is not serialized.” is that means input type as file cant be serialized?

  • Stvlab

    Does anybody know how to send the state of unchecked checkbox? After serialize() If it's checked I've got 'checkbox-name=>on' if it's not I've got nothing… How can I control it?

    Thanks a lot!

  • CtheGood

    New/Return character line textarea problem:
    Is anyone else having this problem? I am trying to submit a form through ajax and .serialize, but there is a textarea in my form, and I need to know when the user has pressed “enter” to start a new line (in PHP, I’m looking for the n or r lines). When you use .serialize though, and you press “enter”, in the $_GET string it doesn’t even put a % in between the line breaks, or anything else to indicate a break in the text.
    Can anybody help me?

  • Dfestin

    serialize shoud retun VALUE ff SELECT not text

  • Alex

    Same problem. Inputs with style=display:none are not serialized.

  • Joshmac

    For some reason this doesn't work:
    $('.input_assignment, #input_paper').serialize()
    it will only serialize the classes (note they are all select's)

    I have also found that having any elements disabled = true will prevent serialization, even if they are hidden fields.

  • Soter13

    I don’t want to serialize the whole form elements, but only checkboxes. Is that possible?

  • Soter13

    OK, I solved it myself:
    $(“:checkbox”).serialize();

  • Dr Fred

    The problem is that serialization should encode a line break as %D0%DA, but jQuery encodes it as %0A.
    The only (graceless) solution i found was to get the form serialized string, then modify it with a replacement function such as :
    function keepLB (str) {
    var reg=new RegExp(“(%0A)”, “g”);
    return str.replace(reg,”%0D$1″);
    }
    Once the serialized string is modified, i send it using the $.post() function…
    Hope it will help !

  • Zarepheth

    Try this plug-in to reverse the serialization. It auto-populates the form elements.

    http://github.com/jakubpawlowicz/jquery.deserialize

  • http://pulse.yahoo.com/_3CLCNGLSWFRBCZP5CRVGERLI34 Mithun

    It would be great if there was an option for uploading files too. Then i wont have to get a extra plugin like jquery form to do that.

  • Tino

    Strange behaviour: user enters text into textarea – text includes URL with protocol e.g. http://abc.com. JSON call fails with 403 forbidden. It seems the the serialised content is being interpreted as a cross domain call (my guess).

    Can anyone suggest how avoid this?

  • http://indeedle.com Leo

    I've noticed this as well. Elements hidden with display:none aren't being serialized which is a bummer.

  • Pradeep

    Hey guys,

    I have a input field with type as button.Can this be serialized??
    example:
    <input name=”mySave” type=”nutton” value=”Save”>
    can above button element serialized??

  • alex

    I just want to ask if .serialize produces results after going to the server? What if the data needs to be validated on the server?

    Thanks

  • http://twitter.com/pronebird Andrew

    This is a standard browsers behavior to ignore display:none fields, isn’t?

  • Alexandre

    1. #input_paper is unique on that webpage? Provide us an example, but is most probably that your form is not well-formatted.

    2. Disabled=true means that the field is disabled and should not be used, w3c standards..

    If you submit a form with something like this:
    <input disabled=”" name=”person” type=”text” value=”my value”>

    Its value WON'T be sent, as the field is disabled. jQuery is just following the rules.

    Keep in your mind:
    - You'll use serialize() instead of submitting form, but will get the exactly same data!
    - When in doubt, disable jQuery and submit your form to see what you'll get.

    Good luck.

  • gavbaa

    No, %0A is correct. That's the standard linefeed/newline character on all platforms, only Windows requires the carriage return as well (%0D) to count as a newline, and it is easily worked around on the server-side for Windows-deployed solutions. This should not be changed.

  • Crafty_Shadow

    A better option:
    $(“input:checkbox”).serialize();

    :checkbox is the same as *:checkbox and this means jQuery will execute “checkbox” == emlement.type for EVERY element in the DOM – pretty slow stuff :)

  • Picasasword

    jquery serialize seems not working in IE. I need to submit a large form via ajax. And, I used 'serialize' for the purpose, but this does not work in IE though it works in firefox, chrome etc. Anybody got a help ? Thanks.

  • Doga

    I'm having massive headaches serializing international characters. I'm updating classic ASP pages which have windows-1252 as charset, when I serialize and send via ajax, my german characters are getting corrupted. Has anyone else run into this? any solutions?

  • Doga

    just in case someone else has this problem, the resolution is to have <%@codepage=65001%> at the top of the receiving page. jquery.serialize() serializes using utf8 and this basically puts the receiving page in the correct codepage

  • Sestrs

    Does this function work on IE6?

  • Guiona

    I use .serialize() to post a form with ajax function. One field is an email address and I can't validate it because @ is transform to %40.
    How I can resolv this “problem”?
    (Sorry for my bad english)

  • Draco

    .serialize doesn't go to the server, it simply returns a query string version of your form that you can send to the server.

  • Draco

    Two options (not necessarily mutually exclusive):

    a) Validate it using javascript before serializing the form.
    b) Pass the email value to your server languages URL decoder method (e.g., Java == URLDecoder.decode(x))

  • mpccolorado

    This post was very helpful to me:
    http://forum.jquery.com/topic/serialize-problem-with-latin-1-iso-8859-1-and-solution

    I need to serialize a form utilizing the encode ISO-8859-1 in jQuery 3.4.2
    I resolve the problem in a similar way to the post above:

    I only need to change the code of JQuery to this:
    line 5435:
    function add( key, value ) {
    // If value is a function, invoke it and return its value
    value = jQuery.isFunction(value) ? value() : value;
    s[ s.length ] = unescape(encodeURIComponent(escape(key))) + “=” + unescape(encodeURIComponent(escape(value)));
    }

  • Xronos I Am

    Jquery`s ajax doesn`t allow files sending. File inputs can`t be serialized

  • Khensolomon

    can we .serialize() div.html?

  • http://tumblrer.com snissen

    Guiona,

    I have been dealing with this exact problem, so I developed a tiny plugin for it at http://robotgarbage.com/atBack…/ Hope that helps

  • https://www.google.com/accounts/o8/id?id=AItOawlF-O-V525BCLKBFFEzn3WsDtvdHnNvDug Vanni
  • Erik504

    It does not seems to serialize type=”number” input fields (tested on Safari and Chrome)

  • Skyrub

    use decodeUriComponent (js global func.); var rowArr = rowArr=$('form').serialize();
    rowArr=decodeURIComponent(rowArr);

  • Skyrub

    whe using serialize() func , it converted special chars to the ascii…

    then i tried the decodeUriComponent(serialized value) (js global func.) and it worked.

    var rowArr=$('form').serialize();

    rowArr=decodeURIComponent(rowArr);

    (my all doc encoding is utf-8)

  • Skyrub

    whe using serialize() func , it converted special chars to the ascii…

    then i tried the decodeUriComponent(serialized value) (js global func.) and it worked.

    var rowArr=$(‘form’).serialize();

    rowArr=decodeURIComponent(rowArr);

    (my all doc encoding is utf-8)

  • http://www.google.com/profiles/Carlos.Vargas.CS golcarcol

    Is there a way for serialize to use an element's ID attribute instead of its NAME attribute?

  • Darkphases

    Good practice to keep your jQuery quick is to ALWAYS descend from the nearest ID.

  • mike

    var editserialize = $('form#edit').serialize();
    editserialize = decodeURIComponent(editserialize.replace(/+/g, ” “))

    data : {
    'data_form' : editserialize
    }

  • VitamineC

    I am fetching a form through ajax, then on submition i am using serialize to fetch the value. This is working great in all browsers except for…drum roll….you know it…IE….any idea why?

  • mike

    is a IE know cache problem, add random number in querystring:

    url: (“content/Option.asp?v=2095032984082347″),