JavaScript URI parameter encoding

When creating a HTTP request in JavaScript, I always used encode() and decode() to pass data between client and server. I also used this approach in PRAjax, my open-source Ajax helper library for PHP.

A developer working with PRAjax on his site reported to me last week that Swedish characters like å, ä, ö, ... were not passed corerctly to and from the server.

My first reaction was: add a UTF-8 header on the server side, and it should work. Characters from other character sets are always displayed correctly when doing that. Except when using JavaScript, it seemed when I tried entering Swedish...

After stepping through my code, I saw everything went wrong after I did encode() on my JavaScript variable. After an hour of different Google searches in the wrong direction, I found out that when using encodeURIComponent() instead of encode(), everything worked fine. It seems like encodeURIComponent() translates more characters than encode().

This is an imported post. It was imported from my old blog using an automated tool and may contain formatting errors and/or broken images.

Leave a Comment