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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With