Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UTF8 encoding not working when using ajax

Tags:

jquery

ajax

utf-8

I recently changed some of my pages to be displayed via ajax and I am having some confusion as to why the utf8 encoding is now displaying a question mark inside of a box, whereas before it wasn't.

Fore example. The oringal page was index.php. charset was explicitly set to utf8 and is in the <head>. I then used php to query the database

Heres is the original index.php page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>Title here</title>
</head>
<body class='body_bgcolor'  >

<div id="main_container">
    <?php 
        Data displayed via php was simply a select statement that output the HTML.  
    ?>
</div>

However, when I made the change to add a menu that populated the "main_container" via ajax all the utf8 encoding stopped working. Here's the new code:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html lang="en">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <title>Title here</title>
    </head>
    <body class='body_bgcolor'  >
<a href="#" onclick="display_html('about_us');"> About Us </a>

    <div id="main_container"></div>

The "display_html()" function calls the javascript page which uses jquery ajax call to retrieve the html stored inside a php page, then places the html inside the div with an id of "main_container". I'm setting the charset in jquery to be utf8 like:

$.ajax({
        async: false,
        type: "GET", 
        url: url, 
        contentType: "charset=utf-8", 
        success: function(data)
            { 
                $("#main_container").html(data);
            }
});

What am I doing wrong?

like image 282
Ronedog Avatar asked May 20 '10 21:05

Ronedog


1 Answers

Encoding is more than specifying the meta tag and content type - the files themselves must really be in the encoding you specify, or you'll get mojibake.

Check that everything is using UTF-8, your database, database connection, table columns. Check that any static files you are including are also encoded in UTF-8.

like image 129
mdma Avatar answered Oct 10 '22 22:10

mdma