AJAX Currency Converter with Google API

No doubt, Google is a magical search engine. Google also provides many APIs to be incorporated in your application. Today, we will use Google’s hidden currency conversion API. Why hidden? Because there is no official documentation for it.

We will build a currency converter from scratch, it pulls data from Google and display the results using jQuery AJAX function. For you better understanding, you may visit demo or download source code below:

Download Source CodeSee Demo

Basically our whole code consist of three components – HTML for displaying interface, Javascript for AJAX functionality and PHP for fetching and manipulating conversion results from Google.

[ad#chitika-460x120]

HTML Structure

HTML structure for this application is simple enough. There are two drop downs, one input field, one button and a div for displaying results. Drop downs are used for selecting From Currency and To Currency while input field is used for entering the desired amount to be converted in your selected currency. Conversion result displays in results div once you click on convert button. When you click on the button, it fires a Javascript function which is described below.

Javascript

Following is the code for our AJAX enabled javascript. Below code is executed upon clicking on convert button.


$(document).ready(function() {

 $('#convert').click(function(){

 //Get all the values
 var amount = $('#amount').val();
 var from = $('#fromCurrency').val();
 var to = $('#toCurrency').val();

 //Make data string
 var dataString = "amount=" + amount + "&from=" + from + "&to=" + to;

 $.ajax({
 type: "POST",
 url: "ajax_converter.php",
 data: dataString,

 success: function(data){
 //Show results div
 $('#results').show();

 //Put received response into result div
 $('#results').html(data);
 }

 });
 });
});

Above code is very simple and should be self explanatory, if you are familiar with jQuery AJAX function. For those who does not know, what’s going on here I tr to explain them.

$(‘#convert’).click(function… this is the starting point of our code, it means that execute the underneath code of this function when an element with id of  ‘convert’ is clicked. In our case this id is used for ‘convert’ button.

After that we grab values from our HTML elements by using .val() function of jQuery and assign these values into Javascript variables. These variables are then used in dataString variable.

In our AJAX function we are using POST method and in ‘url’, we provide the url of our PHP file which will provide conversion results back to this AJAX function. We are sending ‘dataString’ as data to our PHP script.

After successful iterating to our PHP script, this AJAX function first shows our results div and out the received data into our results div as HTML.

[ad#ad-300]

PHP Code

The brain of our application is below PHP code.

<?php
//Get Posted data
$amount = $_POST['amount'];
$from = $_POST['from'];
$to = $_POST['to'];

//make string to be put in API
$string = "1".$from."=?".$to;

//Call Google API
$google_url = "http://www.google.com/ig/calculator?hl=en&q=".$string;

//Get and Store API results into a variable
$result = file_get_contents($google_url);

//Explode result to convert into an array
$result = explode('"', $result);

################################
# Right Hand Side
################################
$converted_amount = explode(' ', $result[3]);
$conversion = $converted_amount[0];
$conversion = preg_replace('/[x00-x08x0B-x1F]/', '', $conversion);
$conversion = $conversion * $amount;
$conversion = round($conversion, 2);

//Get text for converted currency
$rhs_text = ucwords(str_replace($converted_amount[0],"",$result[3]));

//Make right hand side string
$rhs = $conversion.$rhs_text;

################################
# Left Hand Side
################################
$google_lhs = explode(' ', $result[1]);
$from_amount = $google_lhs[0];

//Get text for converted from currency
$from_text = ucwords(str_replace($from_amount,"",$result[1]));

//Make left hand side string
$lhs = $amount." ".$from_text;

################################
# Make the result
################################

echo $lhs." = ".$rhs;
?>

Above code is well commented to make you understand better. In this code we are using some built-in PHP functions – file_get_contents, explode, round and ucwords.

  • In start we grab the values posted to this script by our AJAX function. We store these values into variables.
  • We make a string variable using above explained variables.
  • We concatenate this string variable to Google Currency Calculator API url and store the url in a new variable named $google_url.
  • We fetch the data of $google_url to $result variable using PHP’s file_get_contents function.
  • We receive data from Google something similar to
    {lhs: “1 Euro”,rhs: “1.2692 U.S. dollars”,error: “”,icc: true}
  • Using PHP’s explode function, we separate lhs and rhs from the received response.
  • From rhs we get the converted value and multiply it by our dsired amount to get total conversion.
  • Using PHP’s round function, converted amount is round off to two digits.
  • After this we use PHP’s ucwords function to Capitalize our text’s first letter.
  • We almost do the same for lhs.
  • At last we make results by joining lhs and rhs and echo it to give the results back to our AJAX function.

Last words

In the source code I have applied some CSS to make the user interface better. So don’t be puzzled with the code in source file.

Finally, you have a working Live Currency Converter. You may use this script in your website to attract more visitors. Just play around the code and let me know if you can enhance it further. Please feel free to ask, your comments are always welcome.

If you like this article, please share it on your favorite website. It may help someone somewhere!

[ad#chitika-468x250]

<script type=”text/javascript”><!–
google_ad_client = “ca-pub-7217075623453662″;
/* Tm – 336 x 280 */
google_ad_slot = “2820701010″;
google_ad_width = 336;
google_ad_height = 280;
//–>
</script>
<script type=”text/javascript”
src=”http://pagead2.googlesyndication.com/pagead/show_ads.js”>
</script>

written by +

I believe we learn everyday a new thing and add another experience in our life. Same apply for me…so I share my experiences in the field of web development and design with the hope it will be useful for someone.
Related Posts

47 Responses to "AJAX Currency Converter with Google API"

  1. Shahzaib says:

    Fraz we can make web widget as well from it right or plugin for CMSs?

  2. Fraz Ahmed says:

    Man code is for you, use it as you want :)

  3. Fraz Ahmed says:

    I don’t know why they posted my code over there…..I even do not know about the mentioned website….

    Code is for learning purpose, who cares it is on my website or any other and if they are providing a link back too :)

  4. ghazal says:

    Hi,
    just FYI, I ported Currency Converter to Mootools.
    Download : http://www.box.net/shared/oe0dug4nn7
    Your PHP file has been of a great help.
    Thank you,
    Ghazal

  5. Gebel says:

    Hi Guys,

    Could some one assist me how to save those currencies rates to database table?
    e.g. if EUR=1 then store another currencies rate base on EUR=1
    Thanks in Advance

  6. Fraz Ahmed says:

    @Gebel: You can use $rhs variable to store converted value into database. Later you may use PHP explode to separate currency name and currency rate.

    If you want to save multiple currencies into database for later usage, you should create an array having all required currencies and then wrap a FOR EACH on that array around whole PHP code.

  7. Gebel says:

    Thanks man!

  8. bliss says:

    how can I see the list of available currency codes

  9. Kaz says:

    Love that, I needed solution in asp or .net but I can now convert and have a happy life. great job.

  10. Fraz Ahmed says:

    There is no official documentation so we are not 100% sure what codes are available but on the basis of trial and error we can take our work further.

  11. Fraz Ahmed says:

    Good to see, it works for you!

  12. SLA says:

    hi, i try to convert in demo page, 1 USD to IDR – Indonesian rupiah and resulted 8 IDR. while if i check in http://www.google.com/finance/converter it resulted 8660 IDR. it is big different amount.

    this is awesome, actually and i want to embed to my website but i cannot fix the result. can you help me with this?

    many thanks

  13. Fraz Ahmed says:

    Hi,

    I checked it, you are right. But as I already mentioned, it is not official API by Google. However the problem is that it throws some characters in the result in between of INTEGERS and when we use PHP ’round’ function it takes values until that character comes.

    In your case it returns – 8�695.65217. You can see that after 8 we have some unidentified character. You can get rid of these by commenting out below line at line 25:

    $conversion = round($conversion, 2);

    But then you will have to display the whole value instead of that round one. There might be some other and more efficient solution. I just pointed out the problem and hope you can now use it in your project.

    Happy coding!

  14. Fraz Ahmed says:

    Hey…..now no need to change anything. Just look at line 24. Now It will work fine and will produce valid results.

  15. SLA says:

    hi mate, thanks for updating the code. i’ve tried the new code but, it is still not working for converting USD to IDR.

    thanks,

  16. Chris says:

    Hi guys! I was wondering how should I change the code if I want to use an xml file provided with the currrency rate data instead of Google api? Is it something that can be easily done here?

    Thanks!

  17. Arron Augusto says:

    This code just don’t work.

  18. Benedict says:

    This might be stating the obvious, but I wanted to point out, that the hl parameter changes the language of the result (currency names get translated) and also influences the format of the result. However not all languages seem to be supported.

    Some currencies for example use the dot . as decimal separator, others use it as thousands separator and use the comma , as decimal separator.

    Some examples:

    hl=de
    http://www.google.com/ig/calculator?hl=de&q=100EUR=?AUD
    Output:
    {lhs: “100 Euro”,rhs: “135,875137 Australische Dollar”,error: “”,icc: true}

    hl=fr
    http://www.google.com/ig/calculator?hl=fr&q=100EUR=?AUD
    Output:
    {lhs: “100 euros”,rhs: “135,875137 dollars australien”,error: “”,icc: true}

    hl=en (default?)
    http://www.google.com/ig/calculator?hl=en&q=100EUR=?AUD
    Output:
    {lhs: “100 Euros”,rhs: “135.875137 Australian dollars”,error: “”,icc: true}

  19. AndiD says:

    The Google result unfortuanately is an invalid JSON String.
    So why no turn it into a valid JSON String?

    It is {lhs: “10 Euros” …. and it needs to be {“lhs”:”10 Euros”….
    Fire up some regex!

    Example:

    // google result
    $str = '{lhs: "10 Euros",rhs: "13.8441486 Australian dollars",error: "",icc: true}';
    $str = preg_replace('/(\w+):/', '"\\1":', $str);
    /**
    $str:
    {"lhs": "10 Euros","rhs": "13.8441486 Australian dollars","error": "","icc": true}
    */

    $curr = json_decode($str);
    /**
    $curr:
    stdClass Object
    (
    [lhs] => 10 Euros
    [rhs] => 13.8441486 Australian dollars
    [error] =>
    [icc] => 1
    )
    */

    if($curr){
    if(!$curr->error){
    echo $curr->lhs.' = '.$curr->rhs;
    }
    }

    Have fun!

  20. John says:

    Wow..
    It actually helps me to discover pleasant and valuable information.

    Thanks for sharing

  21. noush says:

    Hi:

    Excellent info but can anyone plz suggest how this can be used in wordpress? I tried but it is not showing any result …

    Thanks

  22. Travel Game: Google Earth is your gameboard | Googiology says:

    [...] Touristo and Skydiver, our first two titles, provide players with the experience of sky diving over the Earth and navigating a Touristo vehicle through exotic locales via Google Earth’s virtual 3D globe. To take advantage of the awesome imagery, terrain, and 3D models available in Google Earth, we built a custom framework that ties into several Google APIs, including Google Earth, Google Maps, and even Google’s currency converter API. [...]

  23. Travel Game: Google Earth is your gameboard - USEFUL PORTAL | USEFUL PORTAL says:

    [...] Touristo and Skydiver, our first two titles, provide players with the experience of sky diving over the Earth and navigating a Touristo vehicle through exotic locales via Google Earth’s virtual 3D globe. To take advantage of the awesome imagery, terrain, and 3D models available in Google Earth, we built a custom framework that ties into several Google APIs, including Google Earth, Google Maps, and even Google’s currency converter API. [...]

  24. [jQuery plugin] 動的に通貨のリアルタイム換算表示を行うjQueryプラグイン | connect-with blog says:

    [...] また、こちらのサイトAJAX Currency Converter with Google API | Tech Mugを参考にすることで基本的な部分の組み立てをすることができました。公開に先立ち筆者と連絡をとろうと思ったのですが、サイトが落ちているようで連絡が取れません。フライングで公開することになってしまいますが、上記サイト筆者との交渉次第でこのプラグインを非公開にすることになるかもしれません。 [...]

  25. wiiisodownload.net says:

    Certainly agree with just what you said. Your explanation was certainly the simplest to comprehend. I tell you, I usually get annoyed any time folks discuss issues that these people obviously dont know about. You were able to hit the nail on the head and spelled out the whole thing with out complication. Perhaps, folks could take a signal. Will likely be back to obtain more. Appreciate it

  26. AJAX Currency Converter with Google API | Techmug | Web Development & Solution Tutorials says:

    [...] Read More Follow On Techmug Posted in: API, Featured, Google, Java Script, Jquery, PHP, Tutorials   Tags: AJAX, API, Converter, Currency, development, Google, Javascript, jQuery, PHP [...]

  27. backlinks says:

    Excellent post. I used to be checking constantly this blog and I am inspired! Extremely useful info specially the ultimate phase :) I deal with such information much. I was looking for this certain information for a long time. Thank you and best of luck.

  28. Phil Hickley says:

    Very educational! Keep up the great work!

  29. newsletter format says:

    I like the helpful information you provide in your articles. I?ll bookmark your weblog and check once more here frequently. I am somewhat certain I will be informed lots of new stuff right right here! Good luck for the next!

  30. Female Weight Loss says:

    Great sharing mate
    i;hv bookmarked it and gonna share it to my friends

  31. Travel Game: Google Earth is your gameboard - BLOG GUIDE – BLOG GUIDE says:

    [...] Touristo and Skydiver, a initial dual titles, yield players with a knowledge of sky diving over a Earth and navigating a Touristo car by outlandish locales around Google Earth’s practical 3D globe. To take advantage of a overwhelming imagery, terrain, and 3D models accessible in Google Earth, we built a tradition horizon that ties into several Google APIs, including Google Earth, Google Maps, and even Google’s banking converter API. [...]

  32. Travel Game: Google Earth is your gameboard | Useful Guide says:

    [...] Touristo and Skydiver, a initial dual titles, yield players with a knowledge of sky diving over a Earth and navigating a Touristo car by outlandish locales around Google Earth’s practical 3D globe. To take advantage of a overwhelming imagery, terrain, and 3D models accessible in Google Earth, we built a tradition horizon that ties into several Google APIs, including Google Earth, Google Maps, and even Google’s banking converter API. [...]

  33. ApnaMobilePackage says:

    Nice and valuable info for wise use.
    Thanks

  34. Sandy says:

    This helped for my college project! thanks

  35. Currency converter using API | xLab says:

    [...] one of such scenario I recently come across Currency converted using Google API by TechMug, this really impressed me a lot. My requirement was to allow users to check the price (default in [...]

  36. Mitch says:

    pity,
    it works only as a stand alone (nothing else but this converter on the page) – the moment i put it on any place on a page that already contains some HTML … and jquery – it won’t work any longer!

    What a pity.

    Cheers

  37. Marcellin says:

    Hi,i like your code. I would like to know u can add burundian franc in the listbox. Or is it possible to use xe.com for real-time currency rate

  38. AJAX Currency Converter with Google API | Tech Mug | Blackberry or Die™ says:

    [...] here: AJAX Currency Converter with Google API | Tech Mug Posted in Gadgets Tags: expand-source, find-brush, rel, stylesheet, syntax, [...]

  39. Daniel says:

    Nice script but it doesn’t work for me. It only returns = 0 for all currencies.

    Regards,
    Daniel

  40. united states says:

    I can’t get over how cool your writing sound is, you need to get to blog more.

  41. Bart says:

    Looks to me that Google blocks the server’s ip after a while. I tried the script on two servers on 2 different domains per server. On one server 2 domains worked. On the other one they both timed out.

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


© Copyright - Tech Mug