Updated: Thank you Rob W for pointing out there was nothing wrong with the code. An error in the backend was found where CHARSET was not yet defined when passing the header(). IE is sensitive about this while Chrome and FF isn’t.
This case can be used for AJAX calls on platforms with dynamic charset support.
—————–
[The original post]
I thought jQuery sorted out browser differences for us. I have absolutely no idea why this works flawlessly in Chrome and FF but not IE.
In Chrome and FF:
The script posts an iso-8859-1 encoded ajax request perfectly. The result is iso-8859-1 encoded and returns nicely.
In IE9
In the backend, depending on the header of (get_address.json.php), I get different results:
// Throws readyState 0 error in IE.
header('Content-type: application/json; charset=iso-8859-1');
// Works in IE9 but strips foreign characters.
header('Content-type: application/json; charset=utf-8');
// Same result as utf-8 above
header('Content-type: application/json');
The script:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("input:button[name=get_address]").click(function() {
$.ajax({
url: "get_address.json.php",
type: "POST",
data: $("input:text[name=crn]").serialize(),
cache: false,
async: false,
dataType: "json",
beforeSend: function(xhr) {
xhr.overrideMimeType("application/x-www-form-urlencoded; charset=<?php echo CHARSET; ?>");
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.readyState + '\n' + textStatus + '\n' + errorThrown.message);
},
success: function(data) {
if (!data) {
alert("Error: No response");
return;
}
if (data.error) {
alert(data.error);
return;
}
$("input:text[name=firstname]").val(data.firstname);
$("input:text[name=lastname]").val(data.lastname);
$("input:text[name=street_address]").val(data.street);
$("input:text[name=postcode]").val(data.postcode);
$("input:text[name=city]").val(data.city);
},
complete: function() {}
});
});
});
</script>
<input type="text" name="crn"> <input type="button" name="get_address" value="Get Address" />
Simulated JSON response (with ISO-8859-1 foreign characters):
<?php
header('Content-type: application/json; charset='. CHARSET);
echo '{"census":"1","protected":"0","crn":"19000000-1234","firstname":"Åke","lastname":"Jönsson","co":"","street":"Testvägen 1","postcode":"72344","city":"Göteborg"}';
?>
The error alert() in IE says:
[object Error]
error
[object Error]
I don’t fancy solutions like converting charsets unless this is the only solution possible. The backend is osCommerce and is purely iso-8859-1.
How can we prevent throwing an error for iso-8859-1 content without character conversion?
Make sure the called script returns a valid content-type charset.