AJAX-enabled exchange rates

February 22nd, 2010 | by Sean |

I finally got round to adding client-side scripting to the Currency Conversion page at spider.my! AJAX is ‘Asynchronous Java And XML’. Basically, it allows you to embed some functionality in your web page so that your page can communicate with your server after it has been rendered in your visitor’s we browser, but without reloading the entire page.

I want to use AJAX for some other projects, so I did some research this morning and used the Currency Conversion page to test it out on. I previously wrote a plain text exchange rate query facility at spider.my which returns only the rate and nothing else. It’s not entirely straightforward to retrieve plain text data using javascript, as far as I can tell. The XMLHttpRequest object that javascript uses to make web requests will only work if it receives a response with a valid XML type, so my text/plain initial effort just isn’t good enough!

A little bit of AJAX on my Currency Conversion page!

A little bit of AJAX on my Currency Conversion page!

If you visit spider.my’s currency conversion page now, you’ll see that the current exchange rate for the two selected currencies is displayed next to the ‘Convert’ button (see image above). Using ‘onchange’ events in the select elements, the page now invokes a javascript function that requests the latest exchange rate from spider.my and updates the displayed rate. That’s a very simple example, but similar code could easily give you an exchange rate widget on your own web pages.

What happens when the selected currencies are changed is that the javascript in the page sends a request to spider.my for the appropriate exchange rate. For example, http://localhost:22791/exchange-rate/GBP-USD.xml is the URL requested for the UK Sterling / US Dollar rate. It’s a very simple response – here it is:

<exchangerate rate="1.5392" source="http://www.ecb.int/stats/eurofxref/eurofxref.zip (Date=19 February 2010)">

All that the javascript has to do is to extract the rate part of the XML response and update the div that holds the visible exchange rate:

var rate = xmlResponse.getElementsByTagName(
"exchangerate")[0].getAttribute("rate");
divRate.innerHTML = '(@'+rate+')';

Easy huh?

I’ve got a better example coming up in the next day or two – stay tuned!

Post a Comment