JQuery - Getting rid of %5B%5D in .serialize()

ajax, forms, jquery, php

Solution

So what you're doing is effectively double-serializing the data.

Once here:

var form_data = $("#form").serialize();

And then again here:

$.ajax({
    type: "POST",
    url: "action.php",
    data: {
        form_data: form_data,
        FrmSubmit: 'SubmitButton'
    },
    cache: true,
    success: function (html) {

        $("#rsvp_sub").html(html);
        alert("form success");
    }
});

When you pass an object into `$.ajax` for the `data` argument, it serializes and encodes it.

So...don't do that. One option is to do this:

var form_data = $("#form").serialize() + "&FrmSubmit=SubmitButton";
$.ajax({
    type: "POST",
    url: "action.php",
    data: form_data,
    cache: true,
    success: function (html) {

        $("#rsvp_sub").html(html);
        alert("form success");
    }
});

Note that if either `FrmSubmit` or `SubmitButton` contained anything other than A-Z, a-z, 0-9 (I'm being conservative), or if you don't control what they contain, you'd want to use `encodeURIComponent`:

var form_data = $("#form").serialize() + "&" +
    encodeURIComponent('FrmSubmit') + "=" +
    encodeURIComponent('SubmitButton');

Problem

I'm using AJAX to submit a serialized form. The data passed on to the `action.php` ends up containing %5B%5D instead of []. Is there anyway of getting back the [], or will the data be able to be handled the same way (i.e. like arrays) in `action.php`? The form is serialized via: ``` var form_data = $("#form").serialize(); ``` Then I send it through `$.ajax`: ``` $.ajax({ type: "POST", url: "action.php", data: { form_data: form_data, FrmSubmit: 'SubmitButton' }, cache: true, success: function (html) { $("#show").html(html); alert("form success"); } }); ``` The ideal data being passed to `action.php` should be something like: `name=JohnSmith&color[]=blue&color[]=yellow&meal[]=chicken&meal[]=fish` I am getting instead: `name=JohnSmith&color%5B%5D=blue&color%5B%5D=yellow&meal%5B%5D=chicken&meal%5B%5D=fish` Additional question: I have also tried .param(), but couldn't really make heads or tails of the data received. Every letter ended up being encoded in a key. Could anyone shed light on why this might be?

Original source

Related problems