[jquery] jQuery AJAX Character Encoding

I'm currently coding a French website. There's a schedule page, where a link on the side can be used to load another day's schedule.

Here's the JS I'm using to do this:

    <script type="text/javascript">
    function load(y) {
        $.get(y,function(d) {
            $("#replace").html(d);
            mod();
        });
    }
    function mod() {
        $("#dates a").click(function() {
            y = $(this).attr("href");
            load(y);
            return false;
        });
    }
    mod();
    </script>

The actual AJAX works like a charm. My problem lies with the response to the request.

Because it is a French website, there are many accented letters. I'm using the ISO-8859-15 charset for that very reason. However, in the response to my AJAX request, the accents are becoming ?'s because the character encoding seems to be changed back to UTF-8.

How do I avoid this? I've already tried adding some PHP at the top of the requested documents to set the character set:

<?php header('Content-Type: text/html; charset=ISO-8859-15'); ?>

But that doesn't seem to work either. Any thoughts?

Also, while any of you are looking here...why does the rightmost column seem to become smaller when a new page is loaded, causing the table to distort and each <li> within the <td> to wrap to the next line?

Cheers

This question is related to jquery ajax character-encoding

The answer is


If you are using CodeIgniter you can solve this by adding the following code to your Controller before loading any Views (assuming you have charsetproperly set on your config. If not, just put charset=whateveryouwant.

$this->output->set_header('Content-type: text/html; charset='.$this->config->item('charset'));

The way I did it was to add that line to the constructor of MY_Controller, my superclass for all Controllers, this way I make sure I will have no encoding problems anywhere.

By the way, this doesn't affect JSON returns (which are encoded in UTF-8).


For my PHP application the solution was include utf8_decode function for each variable get in $_POST.

Ex: (SERVER SIDE)

if( strtoupper($_SERVER['REQUEST_METHOD']) == "POST" ){
$variable = htmlentities($_POST['variable']); // wrong
$variable = htmlentities( utf8_decode($_POST['variable']) ); // right
}

Abraços!!! (Bye Bye!!!)


I had an issue with Swedish/Norwegian letters showing up as question marks, despite having specified:

contentType: "application/json; charset=utf-8",

This was solved by adding encodeURIComponent to the string.

url: "/set_comment.do?text=" + encodeURIComponent(comment),

$str=iconv("windows-1250","UTF-8",$str);

what helped me on the eventually


I DONT AGREE everything must be UTF-8, you can make it work perfectly with ISO 8859, I did, please read my response here.

my response in stackoverflow


I came by this question with exactly the same issue as the asker. The answers here are very informing, and I tried out almost every single one of the suggested answers. None of the answers here worked for me though - there might have been a slight difference in my problem. And that seems to be the case for many. I tried so much before ending up with an answer.

So now I'm adding to the already long list of answers, a solution of my own that solved my kind of encoding problem.

I did just two things. In the database connection script I added:

mysql_set_charset('utf8',$connection);

and apart from that:

  • I changed the encoding of all the files to UTF-8

The point is that everything must be of the same encoding. And when creating new php-files, for the scripts it is not enough just to change the encoding in the script - the file itself must be correctly encoded.


I had a similar problem with ASP with my pages. I've resolved so:

1) Inserted at the begin of the ASP file called by Jquery ajax method the instruction:

Response.Charset = "windows-1252"

In My asp page before the charset wasn't defined and i had saved my file with ANSI encoding (with a text editor as notepad++)

2) In the html file that calls the ASP file with the jquery ajax method i've inserted the parameter content-type that you see below:

$.ajax({         
data: parameters,         
type: "POST",         
url: ajax_url,
datatype: 'html',         
contentType: "text/html;charset=windows-1252",

Briefly, it's important to define in your ASP file called the charset. Strangely, I see that my jquery works with windows-1252 but doesn't work with ISO-8859-1 charset: in this case jquery ajax method give an exception.


I have faced same problem and tried several ways. And i found the solution. If you set request header for "Accept" like below;

$.ajax({
        data: parameters,
        type: "POST",
        url: ajax_url,
        dataType: 'json',
        beforeSend : function(xhr) {
            xhr.setRequestHeader('Accept', "text/html; charset=utf-8");
        },
        success: callback
});

you will see that all the characters seems correct


I was having similar problems, working in a content comments system in our Spanish Portal. What finally solved my problem, after many hours of searching, instead of messing with jQuery charset, that seems to use utf-8 no matter what, it was to decode from utf-8 back to ISO-8859-1 in the PHP that processed the ajax POST. In PHP there is a built in function, utf8_decode(), so the first thing I do with the comments string is this:

$comentario = utf8_decode($_POST['comentario']);

(and then I used nl2br() and htmlentities() PHP functions in order to prepare the text to be stored with html entities instead of special chars)

Good Luck & Peace all over! Seba


jQuery by default assumes UTF-8, to change this default do:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
  $.ajaxSettings.mimeType="*/*; charset=ISO-8859-15";// set you charset
</script>

This works fine for me!... ;))...


I have tried to read a local json/text file using $.ajax and the encoding didn't work at first.. I got it working by saving the json file as UTF-8 encoding. This can be done simply by windows notepad.. use "save as", and then below the file name you can set the encoding to UTF-8.

good luck!


I would strongl suggest the use of the javascript escape() method

you can use this with jQuery by grabbing a form value like so:

var encodedString = escape($("#myFormFieldID").val());

Just changed {"type":"GET"} to {"type":"POST"} and worked like a charm with ISO-8859-1


You need to set up your server to use ISO-8859-15 as the character encoding (adding the appropriate HTTP header). Doing it in the body of the html won't help.

I can see this line

<?php header('Content-Type: text/html; charset=ISO-8859-15'); ?>

at the source of your html. This shouldn't happen. Using Live HTTP Headers I can't see the appropriate charset HTTP header. Use that for both your first page and the ajax service.


I had similar problem. I have text file with json data that has French text. There was always issue displaying some characters. In my case, JavaScript program uses Ajax to retrieve the json text file as follows:

$.ajax({
    async: false,
    type: 'GET',
    url: 'some-url',
    success: function(data, status) {
        mainController.constructionStageMaster = data.records;
     }
});

The returned data always had incorrect accented French letters.

The json text looks as follows:

{
    "records": [
        {
            "StageDesc": "Excavation, Fondation et Bases",
            "Allowed": 9,
            "Completed": 0,
            "TotalCompleted": ""
        },
        {
            "StageDesc": "Étanchement et Remblayage",
            "Allowed": 3,
            "Completed": 0,
            "TotalCompleted": ""
        },
        {
            "StageDesc": "Encadrement et revêtement mural intermédiaire",
            "StageDesc_fr": "Encadrement et revêtement mural intermédiaire np++",
            "StageDesc_fr2": "Encadrement et revêtement mural intermédiaire",
            "Allowed": 15,
            "Completed": 0,
            "TotalCompleted": ""
        }
        ...
    ]
}

Note in the above sample data, the 3rd element, I placed the text with the correct é and incorrect ê French accented letters.

For your information, it seemed that there is some global configuration of Eclipse project using ISO-8859-1 character encoding. In your case it might be different encoding.

After checking the solutions above and playing around with the the project, this is what solved my problem:

  • Find the source of the text which has the correct display of the French text
  • Copy the text
  • Goto Eclipse, open the text file which has the data
  • Right-click the file in the explorer, open properties, and change the encoding to ISO-8859-1
  • Fix the text so that it is displayed properly. Use copy/paste or the keyboard
  • You may have to use the keyboard arrow keys (left/right) to make sure there are no hidden culprit letters that will show-up on HTML with a funny shape. Delete such hidden letter
  • Save the file

Now, in my case, I didn't specify any encoding options in the Ajax call and it works fine. Also, if I change the encoding of the text file with json data, it would still work fine.

Tarek


Specifying the content type on the AJAX-call solved my problems on a Norwegian site.

$.ajax({
        data: parameters,
        type: "POST",
        url: ajax_url,
        timeout: 20000,
        contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
        dataType: 'json',
        success: callback
});

You would also have to specify the charset on the server.

<?php header('Content-Type: text/html; charset=ISO-8859-15'); ?>

I tried many suggestions to read in a textfile with German special characters (ä,ö,ü). In the end:

 $.ajax({
        async:false,
        type: "GET",
        url: "data/FileName.txt",
        dataType: "text",
        contentType: "application/x-www-form-urlencoded;charset=UTF-8",
        success: function (data) {
           alert(data);
        }
    });

let me read in the special characters, but only AFTER I explicitly saved FileName.txt in the UTF-8 format. The standard format for saving text files in the Windows Editor is ANSI and not UTF-8, but it can be changed if you "Save as" and use the dropbox next to the Save-Button or use a better Editor to start with.


If the whole application is using ISO-8859-1, you can modify your jquery.js replacing all occurences of encodeURIComponent by escape (there are 2 occurrences to replace in the current jquery script - 1.5.1)

See encodeUIComponent and escape for more information


When printing out the variables in the ajax file. Put a

htmlentities()

Around them, see if it works. Worked for me in an Icelandic ajax application.


<script type="text/javascript">
  function GetContent(idUser){ 
    $.ajaxSetup({
      url: 'ping.php'
    });

    $.ajax({
      type: "POST",
      url: "blablabla.php",
      dataType: "text",
      data: ({ParamUserID:idUser}),// here we def wich variabe is assiciated
      contentType: "application/x-www-form-urlencoded; charset=iso-8859-1",
      success: function(html) {
        $('#user_specified_content').html(html);
      }
    });     
  }
</script> 

This is the script from which I get my content from the blabla.php page.

When I receive my data on success my accents don't appear.

I have found a super good working solution by my own for fetching data with accents on the fetched data from .success function

On my blabla page. I did this to bring a solution to my problem:

I use utf8_encode(place your data here) in my php file. See it in action below:

while( $row = sqlsrv_fetch_array($recordset) )
{                           
    <option value="<?php echo $row["xyz"]; ?>"><?php echo utf8_encode($row["gName"]) . ' | ' . utf8_encode($row["gManagerName"]); ?></option>                           
}

I´ve had the same problem with pages that:

  • Show up fine when called normally
  • Have the special characters messed up when called via an ajax request

To solve the problem (using php), I used utf8_encode() or htmlentities() on the source data. Both worked, I have used them in different projects.


I have been fiddling around with this problem and found out that this solution works for Firefox and safari (yes, im on a mac at the moment).

when getting the request, i made a content-type=iso-8859-1 here:

if (window.XMLHttpRequest) { // Mozilla, Safari, ...
  httpRequest = new XMLHttpRequest();
        if (httpRequest.overrideMimeType) {
            httpRequest.overrideMimeType('text/xml; charset=ISO-8859-1');
        }
    }

Please tell me if someone finds out this doesn't work in ie.


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to character-encoding

Changing PowerShell's default output encoding to UTF-8 JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10) Change the encoding of a file in Visual Studio Code What is the difference between utf8mb4 and utf8 charsets in MySQL? How to open html file? All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"? UTF-8 output from PowerShell ERROR 1115 (42000): Unknown character set: 'utf8mb4' "for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte How to make php display \t \n as tab and new line instead of characters