Here’s the quick version:
Javascript does NOT automatically URLencode data sent when using AJAX and JSON.
PHP DOES automatically decode url data when it is received.
This little tidbit of knowledge has been driving me crazy for the past 24 hours. The problem I’ve been trying to solve is that of how to properly escape an AJAX request so that special characters like ; and & don’t screw up the AJAX request (if they aren’t escaped, they’ll split the parsing of the single request value into separate variables).
At the same time, I want my application to work properly with UTF-8 encoded characters. When I encoded the AJAX request using encodeURIComponent, I logically assumed that I would also have to use the php urldecode() function. This caused two problems: urldecode doesn’t work with UTF-8 encoded data, and php already assumes the data is url encoded and decodes it automatically for you! So where I was dutifully using urldecode, I was decoding the data a second time, mangling it. So the moral of the tale is: php does decoding for you, so don’t go decoding it a second time unless you have a good reason to.
Post a Comment