Javascript: Encode Data Before AJAX Call Using encodeURIComponent()

After custom building a CMS system I thought I had covered everything in terms of validating the data being entered – so when testing discovered that any string including an ampersand got cut off at the ampersand when saved I was surprised – then immediately realised my rookie error.

The ‘save’ takes place via an AJAX call onchange, the data cleansing obviously happening after the AJAX call occurs, so any data getting passed via the URI in the AJAX call is screwed if the values including ampersands.

An quick and easy fix to this was to use the encodeURIComponent() function in javascript, to encode the url being used in the AJAX call.

encodeURIComponent(uri);

Leave a Reply

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