controlz

alter ego for my blog in Spanish http://formatinternet.wordpress.com …please wait (34% formatted already)…

rails,ajax,charset (i)

Posted by javier ramirez on November 4, 2006

Those programming in non-English languages are used not to have available by default our charset and to work a little extra for everything to work fine.

Rails makes easy to work with UTF-8, but sometimes you just need to work against a legacy database and UTF-8 is not an option. In Rails, if we want to use ISO-8859-1 we can do so by stating the charset in our html code (in the layout) and by adding a controller filter such as

def set_charset
  @headers['Content-Type'] = "text/html; charset=ISO-8859-1"  unless request.xhr?
end

The reason for the unless condition is because if we try to set a content-type of html to an ajax response we will get an error.

If we try this in our application, everything will look fine. No more strange characters and apparently everything is going fine… untill we happen to use ajax.

As I said before, in an ajax response we cannot set html as the content-type; but if we don’t state any type, the browser will just use the default one, so we will be getting strange chars again.

The solution? Just use a content-type of “text/javascript” with the right encoding in your ajax responses. This will tell the browser to treat the response as a javascript with the desired charset.

The modified controller for having a working encoding both for ajax and non-ajax responses would be:

def set_charset
  str_type = request.xhr? ? 'javascript' : 'html'
  @headers['Content-Type'] = "text/#{str_type}; charset=ISO-8859-1"
end

Now we can see all our content, either direct http or through ajax with the right encoding.

… the bad news will come if we want to use ajax for sending content back to the server… but don’t worry too much because I’ll tell you how to fix it in another post.

searchwords: charset, utf-8, iso-8859-1, iconv, prototype.js, javascript, encodeURIComponent, ajax

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.