60

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

Walery Strauch
  • 6,792
  • 8
  • 50
  • 57
Salty
  • 6,688
  • 3
  • 33
  • 31

23 Answers23

67

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'); ?>
Magnar
  • 28,550
  • 8
  • 60
  • 65
  • 2
    that is weird, i had to put contentType: "application/x-www-form-urlencoded;charset=UTF-8" in my ajax call (with jquery form plugin) to fix character encoding in my ISO-8859-1 pages/server – jneira Apr 15 '11 at 07:27
  • 1
    +1 Thanks! I was trying to figure out how to specify a content type with ajax just like the guy above to switch to UTF-8 and u gave me exactly what I needed. – gmustudent Apr 12 '13 at 09:12
  • Thanks for this! Working in a Python/CGI environment, the header I had to provide on the server was the following: `print("Content-Type: text/html; charset=ISO-8859-15 \n")` – sc28 May 19 '17 at 16:31
26

UTF-8 is supposed to handle all accents and foreign chars - why not use it on your data source?

EDIT
[Archive copy of the test file.] with your data

Everything should be UTF-8 in the first place. I loaded the files in notepad++, converted to utf-8 and manually changed the charactes to accents were needed. Once done everything's working like a charm.

BTW, unless your server is defined to php-process .html files, the files you're loading with ajax aren't getting your iso charset. If you insist on using the iso charset, request a php file instead of an html file, and define the charset in the header (not in the file itself)

Divyesh Kanzariya
  • 3,629
  • 3
  • 43
  • 44
yoavf
  • 20,945
  • 9
  • 37
  • 38
  • Doesn't work. Here's the page with a UTF-8 charset: http://www.aquate.us/u/7183981145359693722.jpg As you can see, the accents are still getting butchered. – Salty Feb 16 '09 at 14:35
  • That shouldn't happen. What's your data source? Database? Flat text file? – yoavf Feb 16 '09 at 14:36
  • That's not with the data source, even though the same thing happens. That's if you just load an HTML page with accents on a UTF-8 charset. – Salty Feb 16 '09 at 14:41
  • 1
    Again - shouldn't be a problem. Here's your page converted to utf-8. Eveythings cool, browser has no problems reading it: http://blog.yoavfarhi.com/test.html – yoavf Feb 16 '09 at 14:49
  • I also agree that there shouldn't be a problem with UTF-8. – kgiannakakis Feb 16 '09 at 15:03
  • http://aquate.us/film/horaire.html I have literally copied & pasted the source from your test page, yoavf. No changes. The accents aren't showing =[ – Salty Feb 16 '09 at 15:17
  • You can't copy and past - I hade to manually change the source for the first time for the accents to show up. But once I did, everything is working fine... – yoavf Feb 16 '09 at 15:26
  • What do you mean by manually change the source? I copied the entire source from your test.html and put it in my horaire.html, including the tags where you set the encoding. I'm really sorry for the trouble. :P – Salty Feb 16 '09 at 15:49
  • Pas de problemes :) What editor do you use? you have to make sure your file is saved as utf-8 – yoavf Feb 16 '09 at 16:08
  • @yoavf please check my question as it seems similar to this question and tell me your hints , Thanks in advance http://stackoverflow.com/questions/8238548/how-to-do-the-following-work-scenario-using-php-and-ajax – TopDeveloper Dec 05 '11 at 13:16
  • If data for AJAX is populated from MySQL (for example), putting it in UTF-8 will solve lots of problems: mysql_set_charset('utf8'); – Rafa Sep 13 '15 at 18:37
20
$str=iconv("windows-1250","UTF-8",$str);

what helped me on the eventually

Alfred
  • 21,058
  • 61
  • 167
  • 249
anony
  • 201
  • 2
  • 2
10

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.

kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
8

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());
Doug
  • 6,460
  • 5
  • 59
  • 83
7

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!!!)

Brad Larson
  • 170,088
  • 45
  • 397
  • 571
  • Thanks, Rafael! I hunted for ages trying every suggestion I could find and eventually this solved it for me! utf8_decode was what was missing! Thanks. – BruceHill Aug 06 '11 at 08:41
6

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.

Ólafur Waage
  • 68,817
  • 22
  • 142
  • 198
4

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

Alfred
  • 21,058
  • 61
  • 167
  • 249
4

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),
sth
  • 222,467
  • 53
  • 283
  • 367
yngling
  • 1,376
  • 2
  • 22
  • 34
3

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.

Kyuss
  • 31
  • 1
3

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.

Victor Bocharsky
  • 11,930
  • 13
  • 58
  • 91
Rob
  • 31
  • 1
2

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.

jank
  • 665
  • 6
  • 14
1

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

Community
  • 1
  • 1
Rodrigo Asensio
  • 2,760
  • 4
  • 26
  • 26
1

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!

doron
  • 251
  • 4
  • 12
  • I'm ashamed this actually worked vs. `dataType: "text", contentType: "application/x-www-form-urlencoded;charset=UTF-8"` – franklylately Feb 23 '21 at 16:00
1
<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>                           
}
lulalala
  • 17,572
  • 15
  • 110
  • 169
classics40
  • 71
  • 1
  • 2
0

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

Hüseyin BABAL
  • 15,400
  • 4
  • 51
  • 73
0

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.

Steeven
  • 4,057
  • 8
  • 38
  • 68
0

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).

Christian Dechery
  • 876
  • 10
  • 31
0

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

tarekahf
  • 738
  • 1
  • 16
  • 42
0

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

Alfred
  • 21,058
  • 61
  • 167
  • 249
MauroPorras
  • 5,079
  • 5
  • 30
  • 41
0

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

Jonathan Pasquier
  • 2,561
  • 1
  • 19
  • 17
0

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.

Alfred
  • 21,058
  • 61
  • 167
  • 249
jeroen
  • 91,079
  • 21
  • 114
  • 132
0

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!... ;))...

fwBasic
  • 154
  • 9