Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode/decode UTF-8 in HTTP headers in Rails?

I am using the "insert Rails flash messages into HTTP headers to show Ajax response errors" pattern, like this:

Controller:

 def flash_as_header
   return unless request.xhr?
   [:error, :warning, :notice].each do |type|
    if flash[type]
     response.headers["X-Ajax-#{type.to_s.humanize}"] = flash[type]
    end
   end
 end

JQuery:

 $(document).ajaxComplete(function(response, status, xhr) {
    var types = ["Error", "Notice", "Warning"];
    for (i = 0, l = types.length; i < l; ++i) {
        msg = status.getResponseHeader("X-Ajax-" + types[i]);
        if(msg) {
            break;
        }
    }
    if(msg) {
        $('.flash-error').text(msg).removeClass('is-hidden');
    }
 });

This works, but I am running into character encoding issues. The flash messages contain UTF-8 special characters, and the destination HTML document is UTF-8.

Here is a sample string, as it should appear:

Användare

This is how it in the HTTP response (correct: %C3%A4 is ä):

X-Ajax-Error:Anv%C3%A4ndare

And this is how that outputs in the HTML document:

Användare

That is consistent with this table (http://www.i18nqa.com/debug/utf8-debug.html) which says that "the problem is being caused by UTF-8 bytes being interpreted as Windows-1252 (or ISO 8859-1) bytes."

I am unsure how & where to fix this- in the JQuery function, in the Rails Controller, or in the HTML template?

like image 608
Ali H Avatar asked Sep 03 '25 05:09

Ali H


1 Answers

A combination of escaping & decoding in the Javascript has worked:

I changed this:

 $('.flash-error').text(msg).removeClass('is-hidden');

to this:

$('.flash-error').text(decodeURIComponent(escape(msg))).removeClass('is-hidden');

The output is now correct.

like image 142
Ali H Avatar answered Sep 05 '25 00:09

Ali H