I created a URL using jQuery serialize() and it creates something like this:
client_number=4&start_date&client_number=5
the problem is that I would like to have an url with arrays like this:
client_number[]=4&start_date&client_number[]=5
The [name] of the input elements that are being serialized must contain [] to produce those PHP compatible query strings.
$(function () {
$('form').on('submit', function (e) {
$('pre').text($(this).serialize());
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" name="example1">
<input type="text" name="example1">
<input type="text" name="example2[]">
<input type="text" name="example2[]">
<input type="submit" value="Serialize">
</form>
<pre></pre>
Note: the keys will appear with %5B%5D instead of []. This is expected and OK because that is the proper URL encoding for [].
serialize, then how is this an answer to the question? The question that I linked has this as an answer.serialize is identical to how a browser serializes a form, so jQuery really isn't doing anything unique to merit a separate question.If I understand your question, you want to append [] to the duplicate query string items.
A JavaScript solution would be to use .serializeArray() on the form, mark the key/value pairs which are duplicates, add [] to the the name properties of the duplicates, and then convert the object back to a query string using $.param().
function serializeWithDuplicates(form) {
var pairs = $(form).serializeArray();
for (i = 0; i < pairs.length; i++)
for (j = i + 1; j < pairs.length; j++)
if (pairs[i].name === pairs[j].name)
pairs[i].isDuplicate = pairs[j].isDuplicate = true;
for (i = 0; i < pairs.length; i++)
if (pairs[i].isDuplicate)
pairs[i].name += "[]";
return $.param(pairs);
}
$_GET. Without the[]characters, the behavior is drastically different.