4

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.