blog

Use JavaScript encodeURIComponent function instead of escape for your Ajax application

August 29 2010 by Anya Petersen

Passing variables from JavaScript to a server side language like PHP is a common task at the heart of many Ajax applications. Since the variable will be passed as either post data or a query string, it's important to encode the variable such that it can be decoded correctly on the server side.

I have often seen the JavaScript escape function used for this purpose, but this is NOT the correct answer. escape is not intended for encoding URIs and does not (for example) encode the '+' character. So if you are passing 'you+me' to a PHP script, PHP will decode the data as 'you me'.

In most cases, the method that you want is encodeURIComponent.

Read a more detailed comparison of functions on xks.us.

Anya Petersen

Anya Petersen

Anya likes patterns and finding simple solutions to complicated problems. She has been programming for more than 10 years, picking up degrees in CS and Applied Mathematics along the way.

When not coding, Anya can be found on the track training with one of the world's top roller derby leagues.

Tags