Drupal/AJAX: Exercise caution when using special foreign characters
I was recently working on a Brazilian Drupal 6.x site that uses CCK forms and needed some functionality to map a dropdown select list of states to another dropdown of cities in the chosen state, which I accomplished using a combination of the drupal_json function, as well as jQuery and AJAX, hooked into the drupal menu system.
I learned how to use this functionality quite easily from Pro Drupal Development Chapter 17 - Using jQuery and have implemented it on a number of sites to date. Pro Drupal Development is definitely worth having as a desktop resource.
My problem arose when I was passing special Latin Accented Characters from my client side AJAX calls back to the server side PHP code. Characters like:
á, ã, ç, é, í, ó, etc.
My city dropdown wasn't populating for any states with these special characters in the name. Using the watchdog function back in my callback function and some JS alert statements, I was able to see that, for these states, the included troublesome characters were being 'lost'.
For example, when I selected the state
Ceará an alert box told me the client side JS code was interpreting the value correctly, but my watchdog log showed the state value coming back to the server side from the AJAX call in my JS as
The issue arises in the method used to pass the state back to the PHP side. I was passing the values back using the URL variable (really an URI) in an AJAX call (see aforementioned Pro Drupal Chapter 17). The special characters were getting 'lost'.
I've read about applying different character sets or UTF-8 encodings and the like, but the easiest fix I found was simply wrapping the state value in the JS function encodeURI.
My functionality worked exactly as expected after including this simple fix. HTH.