Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.load() kills character encoding

Tags:

jquery

I'm using the following code to load in content:

<script type="text/javascript">
    jQuery.noConflict();
    jQuery(document).ready(function(){
        jQuery('.content-div').load("all-events.html");     
    });
</script>

However the content is loaded in without the special characters that I want in UTF-8. It was mentioned somewhere to put this at the top of my code:

$html = header('Content-Type: text/html; charset=utf-8'); 

However I only got this error: 'header is not defined'.

like image 980
pufAmuf Avatar asked Oct 28 '11 01:10

pufAmuf


3 Answers

Thanks for the help everyone, however I found what was the problem. The problem was that adding headers to a basic text file didn't change its actual encoding. I wrote that file in notepad and had no way of checking if the encoding was correct. I then opened it in Notepad++ and set the encoding from that application. Hope that helps to others struggling with this problem :)

like image 126
pufAmuf Avatar answered Nov 20 '22 11:11

pufAmuf


I was experiencing the same problem, but the original poster's accepted answer didn't help. Doing one of the bellow actions solved it for me:

  1. Changing the retrieved document's extension from ".html" to ".php".

  2. Adding a .htaccess file to the main directory of the home page with the following content:

    AddDefaultCharset UTF-8
    
  3. A combination of the two above


More about this problem:

Examining response and request headers with Firebug, it was possible to see the server (Apache) was returning content encoded in charset ISO-8859-1. What I needed was UTF-8.

Although all files were encoded as UTF-8 without BOM and

 header("Content-Type: text/html; charset=utf-8");

was being called on the main .php file, the dynamically included .html file had its elements filtered out because jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document, as noted by Mike Haboustak. See jQuery's documentation for load for more details.

like image 27
rslingner Avatar answered Nov 20 '22 10:11

rslingner


jQuery's load() method uses the browser's innerHTML implementation to load the html returned from the request into the current document. This means that the incoming html has to use the same text encoding as the current document. You can't insert UTF-8 characters into an ISO 8859-1 document.

You need to fix this at the server, not in Javascript. The server-side code that is responding with your original Html (that contains your jQuery) needs to include a content-type header with the right character encoding. If you're using Php, I think you've found an example of how to do that.

like image 40
Mike Haboustak Avatar answered Nov 20 '22 10:11

Mike Haboustak