Convert ampersands before serialize()


As jQuery official documentation reports, the .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls.

The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls.

For example, consider to have a form, identified by an id ‘myForm’, with some input fields (e.g. Name, City, Telephone):

<form id=”myForm”>
    <input type=”text” name=”name”/>
    <input type=”text” name=”city”/>
    <input type=”text” name=”telephone”/>
</form>

We can call serialize() function on form fields for example to send values via Ajax POST:

$.post(“ajax/my_function”,{data: $(“#myForm”).serialize()},function(response){parent.location.reload();});

Supposing that input values are ‘Jay’, ‘Nowhere’ and ‘000000000’, the output of serialize() called on jQuery element identified by ‘myForm’ will be a string like “Name=Jay&City=Nowhere&Telephone=000000000”.
On POST reception, it’s easy to get the fields splitting the string with ‘&’ token. In this way we get three fields: Name=Jay, City=Nowhere, Telephone=000000000.

Problems come when one or more fields contain ‘&’. In this case, serialized string value will be “Name=Jay & Silent Bob&City=Nowhere&Telephone=000000000”, so we will obtain four fields after splitting: Name=Jay, Silent Bob, City=Nowhere, Telephone=01296565. So we will have some field not formed as “key=value”.

To avoid this situation, it’s enough to replace ‘&’ chars before serialize() call. To do that, here is the Javascript code:

var ajaxdata = $(“#myForm”).serializeArray().map(function(el) {
    return el.name + “=” + el.value.replace(/&/g, “~”);
}).join(“&”);

By this way, we have replaced all ‘&’ with ‘~’ inside form fields values and then we have concatenated them with ‘&’.
Serialized string will be “Name=Jay ~ Silent Bob&City=Nowhere&Telephone=01296565”.

Splitting by ‘&’ we will obtain three fields: Name=Jay ~ Silent Bob, City=Nowhere, Telephone=000000000. Changing all ‘~’ chars with ‘&’ the final values match the original input. 

Obviously any character that you are confident that will not be used in form fields could be used in place of ‘~’ (DON’T use url encoding special chars like ‘%’).

Leave a comment

Your email address will not be published. Required fields are marked *