Snippets

Create an account or login to be able to add, comment and rate snippets.

Navigation

Decode UTF8 ajax requests

Scriptaculous sends the request parameters always in UTF-8 encoding, regardless of what the page encoding has been set to. This can cause problems with special characters like german umlauts if your general characterset is not set to utf8.

The filter below acts on ajax requests only, converting the parameter values to single-byte ISO-8859-1.

You can enable this filter in your filters.yml by adding the following:

xmlhttpUtf8DecodeFilter:
  class: xmlhttpUtf8DecodeFilter

Below is the code of the actual filter. Store this in the lib directory of your project/application (and do not forget to clean your cache: symfony cc).

<?php
/**
 * This filter acts on AJAX requests and decodes the
 * request parameter values using the php utf8_decode()
 * function.
 * 
 * @author jmunz <jochen.munz@virn.de>
 */
class xmlhttpUtf8DecodeFilter extends sfFilter {
 
    /**
     * Run the filter
     */
    public function execute ($filterChain) {
        $request = $this->getContext()->getRequest();
        // Only act if this is an ajax request
        if ( $request->isXmlHttpRequest() && $this->isFirstCall() ){
            $params = $request->getParameterHolder()->getAll();
            $this->decodeParameters($params);
        }
        // execute next filter
        $filterChain->execute();
    }
 
    /**
     * Decode parameters
     */
    private function decodeParameters(&$params){
        foreach (array_keys($params) as $key) {
            if ( is_array($params[$key]) ) {
                $this->decodeParameters($params[$key]);
            } else {
                $params[$key] = utf8_decode($params[$key]);
            }
        }
    }
 
}
by Jochen Munz on 2006-12-13, tagged ajax  iso88591  utf8 

Comments on this snippet

gravatar icon
#1 Alistair Stead on 2007-01-08 at 08:50

It should be noted that this will cause a problem if the request includes characters that are outside the iso-88591 charset.

I would suggest that websites should always be developed using UTF-8 as you would hope the developers are planning to create a popular application that people may wish to outside of the western world?

gravatar icon
#2 Rodolfo Hernández on 2007-06-28 at 08:22

Vielen dank Jochen,

(die/das/der?) snippet helft mir!

gravatar icon
#3 Kristian Jensen on 2007-11-15 at 01:45

Thank you so much

You need to create an account or log in to post a comment or rate this snippet.