JSON, serialize and UTF-8

handgestrickt had several problems getting client-server communication to work well. the first point is the server-side point, where JSON meets objects and UTF-8. we are using Services_JSON and objects do not become serialized as we expected it. handgestrickt prefers associative arrays (hashes) over objects in our JSON. the german "Umlaute" also made trouble, because they were encoded as UTF-8, but wrongly. the following code helped to solve our problems:

mysql_query("SET NAMES 'utf8'",$db);
$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);

that does the trick. the first command tells MySQL to output UTF-8 and the second one tells the Services_JSON to use associative arrays (hashes) inspite of object-structures for JSON.

the second point is, that we decided to use the PHP-serialization-mechanism on the client-side to transfer huge amounts of structured data to PHP. we prefered this, because PHP has native support for serialize() and unserialize(). the same problems with objects again. we tried several JavaScript solutions, all having problems with UTF-8. in the end we decided for Object.PHP_Serializer and modified the code, so objects are treated as associative arrays (hashes).

var php = new PHP_Serializer(true);
new Ajax.Request('some_script.php',
        {
                method: 'post',
                parameters: {
                        parameter1: 'something',
                        parameter2: 'whatever',
                        parameter3: 'another_nonsense'
                        parameter4: php.serialize(some_object_or_hash)
                },
                asynchronous: true,
                onComplete: function(obj) {
                        alert(obj.responseText);
                }
        }
);

the first line creates the new object, activating full UTF-8 support. the rest is a Prototype.js AJAX request using the serialized data as one parameter. try this at home!

related:
Services_JSON
Object.PHP_Serializer
JSON
UTF-8
PHP
MySQL
JavaScript
serialize()
unserialize()
Prototype.js

Monday, 02. April 2007 • trackback url

Add Comment

( to reply to a comment, click the reply link next to the comment )

Comment Title:
Your Name:
Email Address:
Make Public?
Website:
Make Public?

Comment:


Allowed XHTML tags : a, b, i, strong, code, acrynom, blockquote, abbr. Linebreaks will be converted automatically.


Captcha:

captcha image

please type the content of the above image into the following form-field: