How to encode / decode UTF-8 in HTTP headers in Rails?
I am using "Inserting Rails Flash Messages in HTTP Headers to Display Ajax Error Templates", for example:
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. Flash messages contain special characters UTF-8, and the target HTML document is UTF-8.
Here's an example of a line that should appear:
Användare
This is how it is done in the HTTP response (correct: %C3%A4
yes):
X-Ajax-Error:Anv%C3%A4ndare
And this is how it is displayed in the HTML document:
Användare
This is consistent with this table ( http://www.i18nqa.com/debug/utf8-debug.html ) which says that "the problem is caused by UTF-8 bytes, which are interpreted as Windows-1252 Byte (or ISO 8859- 1)."
I'm not sure how and where to fix this: in a JQuery function, in a Rails Controller, or in an HTML template?
source to share