ISO-8859-1 charset in jQuery.ajax()
Let's get things straight with jQuery Ajax and charset encodings using different browsers.
Send ISO-8859-1 data using jQuery.ajax()
An outgoing jQuery ajax call will always send data encoded in UTF-8. No matter if your meta or form tag says ISO-8859-1. Setting charset in the ajax headers will just be overwritten with UTF-8 . The decoding must be made by the script recceiving the data.
If your script sometimes recceives data from non-ajax components you first need to check if the data is utf-8 encoded. If the encoding is not set you need to identify if the client is an ajax component.
if (!empty($_POST)) {
$flag_unicoded = false;
if (strpos(strtolower($_SERVER['CONTENT_TYPE']), 'charset=utf-8') !== false) $flag_unicoded = true;
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && strpos(strtolower($_SERVER['CONTENT_TYPE']), 'charset') === false) $flag_unicoded = true;
if ($flag_unicoded) {
function utf8_decode_recursive($input) {
$return = array();
foreach ($input as $key => $val) {
if (is_array($val)) $return[$key] = utf8_decode_recursive($val);
else $return[$key] = utf8_decode($val);
}
return $return;
}
$_POST = utf8_decode_recursive($_POST);
}
}
Recceive ISO-8859-1 data using jQuery.ajax()
If no charsets are defined, the ajax component expects the data is UTF-8 encoded. Unless the data was scrambled before it was sent.
1. Headers
If you send a HTTP header stating charset ISO-8859-1, the ajax component returns it nicely transcoded to ISO-8859-1:
Content-type: text/plain; charset=iso-8859-1
If you get your charsets misspelled, Internet Explorer will throw an error while Chrome and Firefox can rely on the overriding mime type (see below).
2. Overriding mime type
If there is no HTTP header stating Content-type, you need to force jQuery to transcode result:
beforeSend: function(jqXHR) {
jqXHR.overrideMimeType("text/html;charset=iso-8859-1");
}
Note: Overriding the mime type does not work in Internet Explorer 9. It will just remove scrambled foreign characters. (Of course, it's Internet Explorer)
To be on the safe side, both override mimetype and send the Content-type header.