The right encoding for your Ajax views

Published on January 17, 2006 and tagged with ajax  cakephp  php  tip

Yesterday, I wrote about my troubles with UTF-8. A very similar problem I had today: the content I requested by Ajax had the wrong encoding. I found the solution relatively fast: I have to set the content type in my Ajax layout. Here is my modified Ajax layout:

<?php
header('Content-type: text/html;charset=UTF-8');
echo $content_for_layout;
?>

16 comments baked

  • Troy Schmidt January 17, 2006 at 15:58

    I am on rev 1806 and I don’t have this problem with my AJAX. I simply request with the ‘/bare’ in front of all my requestactions and AJAX.Updaters and haven’t had a problem yet. Can you go into more detail about the problem this was causing?

    The only problem I have is that I don’t think drag and drop works if you ajax stuff that the div is inside a table cell. And the AJAX code to make that div draggable is inside another div that is called via AJAX. If I refresh the entire page it is fine, but if I use AJAX to refresh the one div and that one has script to activate the other, broken in IE.

  • cakebaker January 17, 2006 at 16:50

    Well, I use rev 1818 of CakePHP, and UTF-8 as encoding for my tables (I create them with CHARSET=utf8) as well as for my html code. The problem was now that German special characters like ä ö ü were not displayed correctly when I got them from the server via Ajax request. Here my code I use to do the Ajax request:

    $ajax->form(’searchform’, array(‘url’ => ‘/users/ajaxSearch’, ‘update’ => ‘results’))

    I cannot say anything about drag and drop since I do not have used it yet. If you experience problems, ask in the IRC channel and/or write a bug report.

  • Felix Geisendörfer January 17, 2006 at 17:42

    Hm if you are going to write a bug report make sure it’s going to the right vendor. Because AFAIK cake uses Prototype/Scriptacoulus for AJAX which is not modified by the Cake Authors in any way.

  • Get Started With AJAX in CakePHP « Ahsan’s Laboratory March 16, 2007 at 20:26
  • Rainer June 15, 2007 at 13:36

    Hey Daniel,

    I’ve tried it out.. not sure why it has got still these ‘?’ for the German special characters… The Firebug Console show me a utf-8 header charset… do you have any ideas??
    PS.: MySQL says: ‘utf8_general_ci’ encoding & Firefox says: UTF-8 encoding ;-)
    Thanks!!

  • cakebaker June 15, 2007 at 17:44

    @Rainer: Do you use UTF-8 for the database connection?

  • Rainer June 17, 2007 at 10:53

    That was the error… Thank you, for your work!!

    i really appreciate this!!

    Greetings, Rainer

  • Rainer June 17, 2007 at 11:01

    That was the error!!

    Thank you, for your nice great work!

    I really appreciate this!!

    Greetings, Rainer

  • cakebaker June 19, 2007 at 08:54

    @Rainer: I am glad to hear that, thanks :)

  • Tim Daldini December 05, 2007 at 22:21

    I’m having the same problem with the ajax autocompleter.

    I found this in the renderAs method from the requesthandlercomponent:
    return $this->respondAs(‘html’, array(‘charset’ => ‘UTF-8′));

    seems like nowadays cake adds the utf header if you add the component in your controller. However, I did some testing, involving returning a list with a single item containing a foreign character (which i just hardcoded in the ajax list view, i did not fetch anything from the database) and the problem still is occuring in both IE and Firefox. Any ideas?

  • cakebaker December 06, 2007 at 19:48

    @Tim: Hm, do you store your files with UTF-8 encoding?

  • Tim Daldini December 09, 2007 at 03:47

    First of all, I found out the requesthandler component only adds the utf header when debug is lower than 2…even though that still didnt solve my problem. ;)

    Furthermore, good question. To be honest, I am in doubt about some stuff regarding UTF-8 and I haven’t really bothered with it that much.

    Is it really required that:
    - The UTF enconding is specified in a meta tag
    - A UTF header is included along with the requested page (php header function)
    - The file itself should also be stored in UTF-8 encoding…which is new to me even though it really makes sense. I’m using dreamweaver at this time, and at first glance it seems files are saved in western european encoding.

    However, I’m uploading all of my files to a local testserver through FTP and I don’t know how that may affect encoding either, so is there a way to check in what what format the stored file is actually encoded on the testserver via a Linux console…or doesnt that make sense?

  • Tim Daldini December 09, 2007 at 06:11

    Fiiinally, adding “encoding” => “utf8″ to the database config basicly solved it.

    this was very hard to debug since putting a string containing special characters simply hardcoded in the ajax view failed as well, which made me think it was not a database related issue, but it was because dreamweaver saved the file in western european encoding by default…

    It also works in debugmode in IE7 and FF even though the utf8 header is not set by the requesthandler (when debug > 1).

    So anyway, thanks!

  • cakebaker December 11, 2007 at 18:37

    @Tim: Good to hear you could solve your encoding issues!

  • Nasir Gulzade April 16, 2009 at 07:14

    Dear All,
    Since I was having trouble with AJAX charset encoding today in the morning with refresh mind I found the solution, the reason why I am posting here is , I searched 2 whole days to find a solution from forums, etc but I could not. however now I am lucky to find the solution for any language just using utf-8 first let mi write my ajax
    My Ajax code is like below:
    not:you can save below code to a page like ajax_post.js

    var xmlhttp_sp = false;
    
    try {
    //If the Javascript version is greater than 5.
          xmlhttp_sp = new ActiveXObject("Msxml2.XMLHTTP");
    
        } catch (e) {
    //If not, then use the older active x object.
    try {
    
           xmlhttp_sp = new ActiveXObject("Microsoft.XMLHTTP");
    
    } catch (E) {
    //Else we must be using a non-IE browser.
                  xmlhttp_sp = false;
                }
    }
    
    if (!xmlhttp_sp &amp;&amp; typeof XMLHttpRequest != 'undefined') {
              xmlhttp_sp = new XMLHttpRequest();
    
    }
    
    function makerequest_sp(serverPage, params, objID)
    {  
        var myRandom=parseInt(Math.random()*99999999);
        
        params+='&amp;'+myRandom;
    
        var url = serverPage;
        //var params = "lorem=ipsum&amp;name=binny";
        xmlhttp_sp.open("POST", url, true);
        //Send the proper header information along with the request
        xmlhttp_sp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        xmlhttp_sp.setRequestHeader("Content-length", params.length);
        xmlhttp_sp.setRequestHeader("Connection", "close");
        xmlhttp_sp.onreadystatechange = function() {//Call a function when the state changes.
        if(xmlhttp_sp.readyState == 4 &amp;&amp; xmlhttp_sp.status == 200) {
            document.getElementById(objID).innerHTML = xmlhttp_sp.responseText;
            //alert(xmlhttp_sp.responseText);  
        }
        }
        xmlhttp_sp.send(params);    
    
        //xmlhttp_sp.send(null); 
    }

    before I was using AJAX with GET method but when I GET form values in my language (farsi Afghanistan) it was just ???? and after using above ajax code I solved my problem.

    //some comments
    function makerequest_sp(serverPage, params, objID)

    when you wanna call makerequest_sp it takes 3 params
    1.serverPage like test.php
    2.params the values of a form like name=nasir&id=34& …
    3.objID is div id where you want to show xmlhttp_sp.responseText inside a div.

    how you call this let me write a function how did I call

    function  test_dari(formid)
    {
     var formvalues = do_it(formid);
    //this do_it  function will retrieve all form name with its value
      url='test.php';
     var params=formvalues+'action=getform&amp;'
      makerequest_sp(url, params, 'mytest'); //here is ajax call function
    }

    any help you want please write to me.
    naser@netlinks.af

  • cakebaker April 16, 2009 at 16:35

    @Nasir: Thanks for sharing!

Bake a comment




(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License