PHP and Ajax with special characters

Added on: Thursday 14th January 2010

Here's a quick tip when using Ajax and PHP to output HTML to a browser. If the code contains special characters such as currency symbols you may get unexpected results.

I was recently working on an ajax script to update our CMS shopping cart and noticed some strange behaviour.

The html for the cart is stored as an editable template to allow it to be styled for different sites. The currency symbols are written into the template.

When the page was first loaded the PHP script processed the template and displayed everything just fine. However, when the cart was updated via the ajax script the currency symbols were replaced in Firefox by the FF FD code for a missing character in a font.

I thought at first that by using the javascript escape function to encode the characters or by using html entity encoding in PHP it would solve the problem. Unfortunately, both of these didn't work.

A quick Google search and I found this article on Roshan's Blog.

The solution is to set the character set in the script that outputs the html to the ajax function using the PHP header function (example below).

header("Content-Type: text/html; charset=iso-8859-1\n");

comments powered by Disqus