Archive for the ‘AJAX’ Category

AJAX Character Encoding in Internet Explorer

Wednesday, July 16th, 2008

Is there no end to the woes of IE?

I’ve just spent 3 hours trying to find out why IE 7 won’t encode my form inputs in UTF-8 before sending them off in an XMLHttpRequest package to my server.

Here’s what is supposed to happen:

I send the page to the browser with UTF-8 character encoding, so the browser is supposed to use this encoding in whatever it does.

This is fine when sending form inputs back to the server with a straight-forward FORM Action routine, but when you use XMLHttpRequest in IE7, IE7 insists on sending the form input in ISO-8859-1.

So if someone enters Ø in one of my form inputs, IE7 sends this off to the server as ‘\xd8′ rather than as ‘%C3%98′ as it should.

The result is that garbage goes into my DB which then invalidates any XML that uses that garbage.

Thankfully, I found a solution.

When I take the form input value from my DOM, I pass it through the Javascript encodeURIComponent function before passing it to the XMLHttpRequest object.

var new_value = document.getElementById(”text_input”).value;
//CONVERT FORM INPUT TO UTF-8 FOR IE 7
new_value = encodeURIComponent(new_value);

XMLHttpRequest is supposed to use UTF-8 by default. There may be something wrong with my set up, but for the life of me I couldn’t get it to use UTF-8 (I’ve checked all my HTTP headers and everything is UTF-8; my server also uses UTF-8 by default, and everything works fine in FF) so this was the only solution that worked.

Another day lost to IE7.

Grrrrr.

Parsing the attributes of XML elements

Monday, November 5th, 2007

PHP 5.0 contains some excellent functions for parsing XML into arrays and objects, but that isn’t much good to you if you have to used PHP 4.0.

That said, it is relatively straightforward to extract the data from between XML tags in PHP 4.0, but the particular problem I came across was having to extract attribute values from the tags themselves. This arose in relation to exchange rate data published by the ECB, which you can view here:

http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml

As you can see, the data we really want (the exchange rate and currency name) is an attribute value rather than raw data between the tags.

Anyway, to get at this data you need to look at the $attrs associative array that is passed to whatever ’start element’ function you are using. This will work (CUBE is the tagname we want in the ECB feed):

function startElement($parser, $name, $attrs) {
global $insidecube, $tag;

if ($insidecube) {
$tag = $name;
} elseif ($name == “CUBE”) {
foreach ( $attrs as $name => $value ) {
echo $name . ” ” . $value . “\n”;
}
$insidecube = true;
}

}

This just prints the attribute keys and values on your screen, but you get the idea.