Euro and other symbols getting mangled by AJAX/Javascript
Another techie post, sorry!
We’ve just added multicurrency invoicing and quotes to our online accounting software. We’re supporting a wide range of currencies and wanted to also allow customers to enter their own.
So you select a currency, by name, from a drop down list. The software then sends out an AJAX request to our server, the server looks up the currency in our database and automatically fills in text boxes with the name, symbol and exchange rate of that currency. You can then overwrite the content of those boxes if you want to.
The Euro symbol and a few others caused us no end of problems. Writing document.getElementById(‘curSymbol’).value=’€’; works fine if the javascript code is on page or in a .js file referenced in the <head> area. However, when it’s sent over http using AJAX, it refused to work and just gave us weird symbols instead.
Google was no help whatsoever so we were left to our own devices.
The first work around we tried was to use javascripts native String.fromCharCode() function with the code for the symbol. This worked for some currency symbols, but not for the Euro.
We finally found a workaround that works for us, so I thought I’d detail it here in the hope it helps some other poor soul.
Our pages already have a .js file that’s included on virtually all of them. So we added a line to this to set up a variable: var symbol_euro=’€’;.
In our database with the currencies, we added a new field called “JSVariable”.
In our AJAX that gets the symbol, we also retrieve the contents of the JSVariable field.
If JSVariable is empty, then we proceed as normal. But if it does contain anything then instead of setting the text box to contain the raw symbol as per the database, we instead set it to the variable.
So instead of document.getElementById(‘curSymbol’).value=’€’;, our code would return document.getElementById(‘curSymbol’).value= symbol_euro; for the Euro symbol.
I hope that makes sense and I hope it saves someone some time.