user1139666
user1139666

Reputation: 1697

jQuery ajax + responseText + Character encoding

I perform an AJAX request to a PHP script in JavaScript and by using the jQuery library.
Here is my command which performs the AJAX request :

$.ajax({
    async: "false",
    cache: "false",
    data: {login: strLogin, password: strPassword},
    datatype: "text",
    error: connexionAjaxError,
    success: connexionAjaxSuccess,
    type: "POST",
    url: "./Connexion"
});

".Connexion" is a URL redirection to my PHP script.
connexionAjaxError is a JavaScript function inevitably executed as soon as the HTTP response is received.
The reason : My PHP script results to a text/plain page with HTTP status code equal to 500.
Here is the most relevant part of my PHP script :

header("HTTP/1.0 500 Internal Server Error; 
        Content-type: text/plain; 
        charset=ISO-8859-1");

echo "été";

Here is the signature of the connexionAjaxError callback function :

function connexionAjaxError(jqXHR, textStatus, errorThrown)

My PHP results to the string "été".
My PHP internal encoding is ISO-8859-1 so the result string is encoded [e9 74 e9] in hexadecimal notation.

But jqXHR.responseText in the connexionAjaxError callback function contains a 1-character string.
I have used the charCodeAt method of the JavaScript String object to get the unicode (UTF-8 ?) code for the character.
The character is encoded 65535 in decimal notation equivalent to [ff ff] in hexadecimal notation.

I do not understand why jqXHR.responseText does not contain the 3-character string "été".
I am not an expert in JavaScript but I suppose jqXHR.responseText can only contains a string encoded in UTF-8.
So the string "été" in jqXHR.responseText would be encoded [c3a9 74 c3a9] in hexadecimal notation.
I have retrieve the UTF-8 code for the character "é" from the following web site : http://www.utf8-chartable.de/

Upvotes: 2

Views: 3747

Answers (2)

fsodano
fsodano

Reputation: 548

I make a lot of development in Spanish and I've noticed a few things that might help you, since I've gone through this already:

The charset in the header function should be UTF-8.

Also, the FILE itself (the PHP script) must be saved in UTF-8, you can easily achieve this if you edit the file with Notepad++ and select the encoding to be UTF-8 without BOM.

Same goes for your javascript and HTML files, they should all be encoded with UTF-8 without BOM rather than ANSI.

Let me know!

Upvotes: 1

optimisticupdate
optimisticupdate

Reputation: 1689

Try to set the Contenttype like this in your call, as far as I know jQuery Ajax is always utf-8 if not specified.

$.ajax({
...
    datatype: "text",
    contentType: "application/x-www-form-urlencoded;charset=ISO-8859-1",
    error: connexionAjaxError,
    success: connexionAjaxSuccess,
    type: "POST",
...
});

Edit: If my answer isn't helpfull, it might help if you check the servers charset configuration, and also post it.

Upvotes: 0

Related Questions