How To Create An Exchange Rate Money Converter With Money.js

Update: 19/10/2012 You now have pay for the open exchange rates API. If you want to use this code on any future projects you will need to signup for an API key https://openexchangerates.org/signup. For this reason the demo on this pay will no longer work. The code is still valid but you will need to buy an API key.

In today's tutorial we are going to work with a Javascript library which allows you to easily deal with money in any web application.

Money JS

This JavaScript file will allow you to create an online application to easily convert from one currency to another using only one function.

Update To Date Values

This file keeps up to date with the ever changing exchange rates in currency by using the Open Source Exchange API. The API service will simply get all the latest exchange rates once an hour from the Google Calculator API and store the results in a JSON format repository on Github.

Download

The money.js comes with 2 download types the full version or the minified version.

»  money.js development version (4.3 kb)

»  money.min.js production/minified version (1.1 kb)

Installation

To install Money.js it couldn't be easier it's simply a standalone Javascript file so all you have to do is include the Javascript file on your pages.

<script src="money.js"></script>

Setting Up The Converter

Before you can start converting currencies you need to setup which currencies you want to convert.

For this you define a base rate and all the currencies you may want to convert. Which is defined by using the base and rates properties on the money.js library.

The rates can have multiple currencies and values. The values you enter in here will be the exchange rates that will convert your base currency.

fx.base = "USD";
fx.rates = {
	"EUR" : 0.74510096, // eg. 1 USD === 0.74510096 EUR
	"GBP" : 0.64771034,
	"HKD" : 7.78191949,
	"USD" : 1,          // always include the base rate (1:1)
	/* etc */
}

This would mean static setting of the exchange rates which is one of the problems with converting the exchange rates. Therefore you need to access the Open Source Exchange Rates from the API via AJAX call so you can get the up to date exchange rates.

Using jQuery you can access the API by using the following snippet.

<script type="text/javascript">
    // Load exchange rates data via the cross-domain/AJAX proxy:
    $.getJSON(
        'http://openexchangerates.org/latest.json',
        function(data) {
            // Check money.js has finished loading:
            if ( typeof fx !== "undefined" && fx.rates ) {
                fx.rates = data.rates;
                fx.base = data.base;
            } else {
                // If not, apply to fxSetup global:
                var fxSetup = {
                    rates : data.rates,
                    base : data.base
                }
            }
        }
    );
</script>

The problem with getting the values is way is that your page will return before the exchange rates have been populated from the API, so your visitors could make changes before the rates have been setup. The better option is to use the server side to populate these variables.

Here is a PHP way to populate the rates.

<?php
// Required file, could be e.g. '/historical/2011-01-01.json' or 'currencies.json'
$filename = 'latest.json';

// Open CURL session:
$ch = curl_init('http://openexchangerates.org/' . $filename);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Get the data:
$rates = curl_exec($ch);
curl_close($ch);

$exchange = json_decode($rates);

?>
<!-- assuming you've already loaded money.js, above -->
<script type="text/javascript">
	fx.rates = {<?php echo json_encode($exchange->rates); ?>};
	fx.base = "<?php echo $exchangeRates->base; ?>";
</script>

Setup Default Convert Values

After the money.js has loaded you will need to setup a default convert of currencies, this is done by using the fx.settings property.

// Using `fx.settings` (must be after loading the library)
fx.settings = {
	from : "GBP",
	to : "EUR"
};

Convert Currencies

Now that the money.js has been loaded and the settings are in place we can now convert the currencies.

If you setup the library to use the default GBP to EUR then all you have to do is call the function convert(value) and the value passed in will be converted from GBP to EUR.

// Using `fx.settings` (must be after loading the library)
fx.settings = {
	from : "GBP",
	to : "EUR"
};

fx.convert(1000);

You can change which values it changes to by passing in additional options to the convert method.

fx.convert(1000, {to: "USD" });
fx.convert(1000, {from: "USD", to: "GBP" });

fx Conflicts

Along with many Javascript libraries they use namespaces to separate there code from other libraries.

For money.js it uses the namespace fx by default.

fx.convert(1000, {to: "USD" });
fx.convert(1000, {from: "USD", to: "GBP" });

The problem comes if you have other libraries also using the namespace fx, you can get function conflict errors. To get around this you need to change the namespace being used by money.js.

// Assign the money.js library to a global money object:
var money = fx.noConflict();

// `fx` is now back to whatever it was before money.js was loaded, and you can still use the library via the `money` reference, like so:
money.convert(5318008);
money.settings.from = "JPY";
money(5318008).to("HKD");

Creating A Currency Exchange Application

Now we know that we can use the money.js to convert different currencies we can easily use this to make a web application to do this for us.

Convert Your Money

View the demo to see this in action.

Demo

The PHP

First we need to setup the PHP functions to get the data from the open source exchange APIs, we can then use this data to populate drop downs with the currencies and populate the rates.

As we are going to make 2 calls to the open source exchange API we are going to create a function to return the JSON data.

/**
 * Make a call to the open exchange API
 * 
 * @param $filename
 * What data to collect
 * 
 * @return
 * JSON Data
 */
function getOpenExchangeRates($filename){
		
	// Open CURL session:
	$ch = curl_init('http://openexchangerates.org/' . $filename);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	
	// Get the data:
	$json = curl_exec($ch);
	curl_close($ch);
	
	return json_decode($json);
}

We also need to make a function to create a drop down of all the currencies, the following will make a call to the API, return all currencies, loop through them and create options for the select dropdown.

/**
 * Get all the currency options
 * 
 * @param $default
 * Selected currency
 * 
 * @return
 * Echo the select options
 */
function getCurrencyOptions($default){
	
	$currencies = getOpenExchangeRates('currencies.json');
	
	foreach($currencies as $k => $v){
		$selected = '';

		if($k == $default){
			$selected = "selected='selected'";
		}	

		echo '<option '.$selected.' value="'.$k.'">'.$v.'</option>';	
	}
}

Creating The Form

Below is the HTML that we are using for our application as you can see where we are including the javascript files we call the PHP functions we created to above. This will populate the fx.rates variable and the fx.base variable with the data from the open source exchange API.

We are creating a form to use on our application we need two textboxes, two select boxes and a button. For the select boxes options we are using the other PHP function created above to populate it with all of currencies available.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="core.css">


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script src="./js/money.js"></script>

<?php $exchangeRates = getOpenExchangeRates('latest.json'); ?>
<script type="text/javascript">
	fx.rates = <?php echo json_encode($exchangeRates->rates); ?>;
	fx.base = "<?php echo $exchangeRates->base; ?>";
</script>
<script src="core.js"></script>

</head>
<body>

<section class="container">

<div class="form">
	<h3>Exchange Currency</h3> 
	
	<p>From</p>
	<p><input type="text" name="money" id="money" value="100" /><select id="country_from">
			<?php getCurrencyOptions("USD"); ?>
	</select></p>
	<p>To</p>
	<p> <input type="text" name="exchange_total" id="exchange_total" /><select id="country_to">
			<?php getCurrencyOptions("GBP"); ?>
	</select></p>
	<p> <input type="button" name="exchange" id="exchange" value="Exchange" /></p>
</div>

</body>
</html>

Styling The Form

The styling of this form is very simple it's just going to be a small form so we are going to create lots of space by applying padding to the form elements.

body, h2, h3{
	font-family: 'Arvo', serif;
	color:#444;
	font-size:1.6em;
}
.container{
	width:90%;
	margin:30px auto;
	padding:25px;
	min-height:400px;
	height:auto;	
}
select, input{
	padding:10px;
	border:1px solid #a1a1a1;
	font-size:14px;
}
#exchange{
	padding:15px;
	width:250px;
}
.form{
	text-align:center;
	width:70%;
	margin:0 auto;
	border-radius:10px;
	-moz-border-radius:10px;
	-webkit-border-radius:10px;
	border:1px solid #a1a1a1;
	padding:40px;
}

Converting The Money

Now we have all the data we need we can do the jQuery to access the money.js library and convert the two values.

This will happen on the click event of the exchange button, first we setup the settings by applying the from and to currencies, these values come from the two drop downs.

With the settings populated all we have to do is call the convert function to change the value from one currency to another by passing in the value of the first textbox (money).

With the converted value being stored in a variable we can add this into the total textbox to display the converter value to the user.

$(document).ready(function(){
	$('#exchange').click(function(){		
		fx.settings = { from: $('#country_from').val(), to: $('#country_to').val() };
		var change = fx.convert($('#money').val());
		
		$('#exchange_total').val(change);
	});
});

That's all you need to convert the different exchange rates as the money will do all the hard work for you.

View the demo to see this in action.

Demo

I have started to use Github for my demo files so you can now download all my newest tutorials from github. This is the first one available demo. Please follow me on Github to stay up to date with all new demos.

Download

Create Your Own Money Converter

If you want to create your own application then you will need the money.js files download them from the links below.

»  money.js development version (4.3 kb)

»  money.min.js production/minified version (1.1 kb)

Advertise here

Comment