185

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 Commented Jan 31, 2017 at 12:48

8 Answers 8

321

There's a function that does exactly this:

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

var data = $('form').serialize();
$.post('url', data);
Sign up to request clarification or add additional context in comments.

6 Comments

$.post also can call a function on success. $.post('url', data, function() { .... });
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.
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 ?
@FranciscoCorralesMorales name your inputs like this way: person[0].firstName person[0].lastName person[1].firstName person[1].lastName
@ahmehri, so is this a valid HTML <input name="person[1].lastName"> ?
|
89

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
        }
    });

5 Comments

Yes it's supported by updated browsers but by using serialized you can only pass strings.
Maybe you should mention that in your answer
you beauty! worked like charm (form data + file upload)
can't emphasize this enough! tried form.serialize() but it just didn't work for file upload. new FormData(this) worked nicely
Is it possible to extract the url from the "action" attribute of the form for example with url: myform.action?
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 Comments

If you are using PHP it is trivial to parse a querystring using parse_url function: us3.php.net/manual/en/function.parse-url.php
I know this is old but how do u know which option(s) were selected using this method?
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.

Comments

6

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 Comment

To extract the url from the "action" attribute of the form use url: $(this).attr('action'), instead
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>

Comments

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;
}

Comments

-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)
        }
    });
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.