on Basics Tutorials

Building an AJAX currency converter with PHP, jQuery and Google

16 comments
currency-exchange-480
Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon

As you may already know, Google has a calculator feature built in their search engine, which can be used to convert measures, currencies, get stock quotes, weather data and many other features. You can see this features explained here.

Why wouldn’t we use it for something useful and build a simple AJAX currency converter using Google currency converter feature? We need some time, jQuery, Google, great music and of course, this tutorial.


So, let’s start. Create new file, call it index.php and make some basic markup for our converter:

<label for="amount">Amount:</label>
        <input class="amount" type="text" name="amount" id="amount" value="100" />

    

        <label for="from">From:</label>
        <select name="from" id="from">
          <option selected="selected" value="EUR">Euro - EUR</option>
          <option value="USD">United States Dollars - USD</option>
          <option value="GBP">United Kingdom Pounds - GBP</option>
          <option value="CAD">Canada Dollars - CAD</option>
          <option value="AUD">Australia Dollars - AUD</option>
          <option value="JPY">Japan Yen - JPY</option>
          <option value="INR">India Rupees - INR</option>
          <option value="NZD">New Zealand Dollars - NZD</option>
          <option value="CHF">Switzerland Francs - CHF</option>
          <option value="ZAR">South Africa Rand - ZAR</option>
          <option value="DZD">Algeria Dinars - DZD</option>
          <option value="ARS">Argentina Pesos - ARS</option>
          <option value="AUD">Australia Dollars - AUD</option>
          <option value="BHD">Bahrain Dinars - BHD</option>
          <option value="BRL">Brazil Reais - BRL</option>
          <option value="BGN">Bulgaria Leva - BGN</option>
          <option value="CAD">Canada Dollars - CAD</option>
          <option value="CLP">Chile Pesos - CLP</option>
          <option value="CNY">China Yuan Renminbi - CNY</option>
          <option value="CNY">RMB (China Yuan Renminbi) - CNY</option>
          <option value="COP">Colombia Pesos - COP</option>
          <option value="CRC">Costa Rica Colones - CRC</option>
          <option value="HRK">Croatia Kuna - HRK</option>
          <option value="CZK">Czech Republic Koruny - CZK</option>
          <option value="DKK">Denmark Kroner - DKK</option>
          <option value="DOP">Dominican Republic Pesos - DOP</option>
          <option value="EGP">Egypt Pounds - EGP</option>
          <option value="EEK">Estonia Krooni - EEK</option>
          <option value="EUR">Euro - EUR</option>
          <option value="FJD">Fiji Dollars - FJD</option>
          <option value="HKD">Hong Kong Dollars - HKD</option>
          <option value="HUF">Hungary Forint - HUF</option>
          <option value="ISK">Iceland Kronur - ISK</option>
          <option value="INR">India Rupees - INR</option>
          <option value="IDR">Indonesia Rupiahs - IDR</option>
          <option value="ILS">Israel New Shekels - ILS</option>
          <option value="JMD">Jamaica Dollars - JMD</option>
          <option value="JPY">Japan Yen - JPY</option>
          <option value="JOD">Jordan Dinars - JOD</option>
          <option value="KES">Kenya Shillings - KES</option>
          <option value="KRW">Korea (South) Won - KRW</option>
          <option value="KWD">Kuwait Dinars - KWD</option>
          <option value="LBP">Lebanon Pounds - LBP</option>
          <option value="MYR">Malaysia Ringgits - MYR</option>
          <option value="MUR">Mauritius Rupees - MUR</option>
          <option value="MXN">Mexico Pesos - MXN</option>
          <option value="MAD">Morocco Dirhams - MAD</option>
          <option value="NZD">New Zealand Dollars - NZD</option>
          <option value="NOK">Norway Kroner - NOK</option>
          <option value="OMR">Oman Rials - OMR</option>
          <option value="PKR">Pakistan Rupees - PKR</option>
          <option value="PEN">Peru Nuevos Soles - PEN</option>
          <option value="PHP">Philippines Pesos - PHP</option>
          <option value="PLN">Poland Zlotych - PLN</option>
          <option value="QAR">Qatar Riyals - QAR</option>
          <option value="RON">Romania New Lei - RON</option>
          <option value="RUB">Russia Rubles - RUB</option>
          <option value="SAR">Saudi Arabia Riyals - SAR</option>
          <option value="SGD">Singapore Dollars - SGD</option>
          <option value="SKK">Slovakia Koruny - SKK</option>
          <option value="ZAR">South Africa Rand - ZAR</option>
          <option value="KRW">South Korea Won - KRW</option>
          <option value="LKR">Sri Lanka Rupees - LKR</option>
          <option value="SEK">Sweden Kronor - SEK</option>
          <option value="CHF">Switzerland Francs - CHF</option>
          <option value="TWD">Taiwan New Dollars - TWD</option>
          <option value="THB">Thailand Baht - THB</option>
          <option value="TTD">Trinidad and Tobago Dollars - TTD</option>
          <option value="TND">Tunisia Dinars - TND</option>
          <option value="TRY">Turkey Lira - TRY</option>
          <option value="AED">United Arab Emirates Dirhams - AED</option>
          <option value="GBP">United Kingdom Pounds - GBP</option>
          <option value="USD">United States Dollars - USD</option>
          <option value="VEB">Venezuela Bolivares - VEB</option>
          <option value="VND">Vietnam Dong - VND</option>
          <option value="ZMK">Zambia Kwacha - ZMK</option>
        </select>

    

        <label for="to">To:</label>
        <select name="to" id="to">
          <option value="USD">United States Dollars - USD</option>
          <option value="GBP">United Kingdom Pounds - GBP</option>
          <option value="CAD">Canada Dollars - CAD</option>
          <option value="AUD">Australia Dollars - AUD</option>
          <option value="JPY">Japan Yen - JPY</option>
          <option value="INR">India Rupees - INR</option>
          <option value="NZD">New Zealand Dollars - NZD</option>
          <option value="CHF">Switzerland Francs - CHF</option>
          <option value="ZAR">South Africa Rand - ZAR</option>
          <option value="DZD">Algeria Dinars - DZD</option>
          <option value="ARS">Argentina Pesos - ARS</option>
          <option value="AUD">Australia Dollars - AUD</option>
          <option value="BHD">Bahrain Dinars - BHD</option>
          <option value="BRL">Brazil Reais - BRL</option>
          <option value="BGN">Bulgaria Leva - BGN</option>
          <option value="CAD">Canada Dollars - CAD</option>
          <option value="CLP">Chile Pesos - CLP</option>
          <option value="CNY">China Yuan Renminbi - CNY</option>
          <option value="CNY">RMB (China Yuan Renminbi) - CNY</option>
          <option value="COP">Colombia Pesos - COP</option>
          <option value="CRC">Costa Rica Colones - CRC</option>
          <option value="HRK">Croatian Kuna - HRK</option>
          <option value="CZK">Czech Republic Koruny - CZK</option>
          <option value="DKK">Denmark Kroner - DKK</option>
          <option value="DOP">Dominican Republic Pesos - DOP</option>
          <option value="EGP">Egypt Pounds - EGP</option>
          <option value="EEK">Estonia Krooni - EEK</option>
          <option value="EUR">Euro - EUR</option>
          <option value="FJD">Fiji Dollars - FJD</option>
          <option value="HKD">Hong Kong Dollars - HKD</option>
          <option value="HUF">Hungary Forint - HUF</option>
          <option value="ISK">Iceland Kronur - ISK</option>
          <option value="INR">India Rupees - INR</option>
          <option value="IDR">Indonesia Rupiahs - IDR</option>
          <option value="ILS">Israel New Shekels - ILS</option>
          <option value="JMD">Jamaica Dollars - JMD</option>
          <option value="JPY">Japan Yen - JPY</option>
          <option value="JOD">Jordan Dinars - JOD</option>
          <option value="KES">Kenya Shillings - KES</option>
          <option value="KRW">Korea (South) Won - KRW</option>
          <option value="KWD">Kuwait Dinars - KWD</option>
          <option value="LBP">Lebanon Pounds - LBP</option>
          <option value="MYR">Malaysia Ringgits - MYR</option>
          <option value="MUR">Mauritius Rupees - MUR</option>
          <option value="MXN">Mexico Pesos - MXN</option>
          <option value="MAD">Morocco Dirhams - MAD</option>
          <option value="NZD">New Zealand Dollars - NZD</option>
          <option value="NOK">Norway Kroner - NOK</option>
          <option value="OMR">Oman Rials - OMR</option>
          <option value="PKR">Pakistan Rupees - PKR</option>
          <option value="PEN">Peru Nuevos Soles - PEN</option>
          <option value="PHP">Philippines Pesos - PHP</option>
          <option value="PLN">Poland Zlotych - PLN</option>
          <option value="QAR">Qatar Riyals - QAR</option>
          <option value="RON">Romania New Lei - RON</option>
          <option value="RUB">Russia Rubles - RUB</option>
          <option value="SAR">Saudi Arabia Riyals - SAR</option>
          <option value="SGD">Singapore Dollars - SGD</option>
          <option value="SKK">Slovakia Koruny - SKK</option>
          <option value="ZAR">South Africa Rand - ZAR</option>
          <option value="KRW">South Korea Won - KRW</option>
          <option value="LKR">Sri Lanka Rupees - LKR</option>
          <option value="SEK">Sweden Kronor - SEK</option>
          <option value="CHF">Switzerland Francs - CHF</option>
          <option value="TWD">Taiwan New Dollars - TWD</option>
          <option value="THB">Thailand Baht - THB</option>
          <option value="TTD">Trinidad and Tobago Dollars - TTD</option>
          <option value="TND">Tunisia Dinars - TND</option>
          <option value="TRY">Turkey Lira - TRY</option>
          <option value="AED">United Arab Emirates Dirhams - AED</option>
          <option value="GBP">United Kingdom Pounds - GBP</option>
          <option value="USD">United States Dollars - USD</option>
          <option value="VEB">Venezuela Bolivares - VEB</option>
          <option value="VND">Vietnam Dong - VND</option>
          <option value="ZMK">Zambia Kwacha - ZMK</option>
        </select>

    

        <input type="button" name="submit" id="submit" value="Convert" />
        
        <div id="results"></div>

Basically, we have two drop downs with currencies, amount field and a button. Below is a div with id results which will hold our result data.

Now let’s add some jQuery to handle AJAX call and filling result data into our markup:

$(document).ready(function() {
    
    $('#submit').click(function(){
     
     //Get the values
     var amount     = $('#amount').val();
     var from       = $('#from').val();
     var to         = $('#to').val();
     
     var params = "amount=" + amount + "&amp;amp;from=" + from + "&amp;amp;to=" + to;
     
     $.ajax({
       type: "POST",
       url: "convert.php",
       data: params,
       success: function(data){
            $('#results').html(data);
       }
     });
    });
});

We are making an ajax call to convert.php and on success filling the data into results div.

And here is convert.php :

// sanitizing input using built in filter_input available from PHP 5.2
    $amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_INT);
    $from   = filter_input(INPUT_POST, 'from', FILTER_SANITIZE_SPECIAL_CHARS);
    $to     = filter_input(INPUT_POST, 'to', FILTER_SANITIZE_SPECIAL_CHARS);
    
    // building a parameter string for the query
    $encoded_string = urlencode($amount) . urlencode($from) . '%3D%3F' . urlencode($to);
    
    $url = 'http://www.google.com/ig/calculator?hl=en&amp;amp;q=' . $encoded_string;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);

    $results = curl_exec($ch);
    
    
    // this is json_decode function if you are having PHP < 5.2.0
    // taken from php.net
    $comment = false;
    $out = '$x=';
   
    for ($i=0; $i<strlen($results); $i++)
    {
        if (!$comment)
        {
            if ($results[$i] == '{')            $out .= ' array(';
            else if ($results[$i] == '}')       $out .= ')';
            else if ($results[$i] == ':')       $out .= '=>';
            else                                $out .= $results[$i];           
        }
        else $out .= $results[$i];
        if ($results[$i] == '"')    $comment = !$comment;
    }
    // building an $x variable which contains decoded array
    echo eval($out . ';');
    
    echo $x['lhs'] . ' = ' . $x['rhs'];

This code is pretty simple and commented, but let me explain some stuff I added.

$amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_INT);
$from = filter_input(INPUT_POST, 'from', FILTER_SANITIZE_SPECIAL_CHARS);
$to = filter_input(INPUT_POST, 'to', FILTER_SANITIZE_SPECIAL_CHARS);

Above code is really interesting. It can be used from PHP 5.2.0 and above. The filter_input() function gets external variables (like form input) and filters them.

This function is used to validate variables form insecure sources such as user input.

You can filter several sources:

  1. INPUT_GET
  2. INPUT_POST
  3. INPUT_COOKIE
  4. INPUT_ENV
  5. INPUT_SERVER

It returns the filtered data on success, FALSE on failure or NULL if the variable parameter is not set.

You can expand this to convert a currency and save it to database, so you never ever have to worry about prices on your webshop.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon



  • Pingback: Tweets that mention Building an AJAX currency converter with PHP, jQuery and Google | CodeForest -- Topsy.com()

  • Mohamed Zeid

    Very cool. Thank you for sharing.

  • David Duran

    i get this error PHP Parse error: syntax error, unexpected ‘;’ in /home/forumed/public_html/counter/currency/convert.php(39) : eval()’d code on line 1

    can you tell me why, or what i am doing wrong?

  • Good article, I’m going to learn AJAX

  • Chris

    Hi ! 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!

    • Hi Chris, unfortunately there is no quick change in code that would help you with that.

      As you can see, Google is returning JSON and you need to parse an XML file. But, check out the SimpleXML library on Google, it could help you. ( http://php.net/manual/en/book.simplexml.php )

  • Marco

    Hi there, this is a nice script. I have found a ton of this scripts but they all use a one simple conversion with input boxes and submit buttons.

    Is there any way to adapt this code so it can change several prices at once ?

    Imagine you have a html table with several prices and you want to convert all the prices at once to a certain currency by clicking a country flag or selecting via select list.

    Now, that would be a “killer” !

    Thanks for any help !

  • acid

    Fatal error: Call to undefined function curl_init() in Z:homelocalhostwwwPhp_lesson1convert.php on line 14
    what is the problems???

    • Probably Curl library is not installed on the server. Contact your hoster.

  • noush

    Goof info

    Do you have any idea how to integrate this in wordpress?

    Thanks

  • Dave

    Hi there.
    This is great stuff.
    One bug though:
    With values greater than 999, the code inserts a comma (presumably), which is turnig out as an undefined character (‘?’ in a diamond (Firefox utf-8)
    Looks like this: 1�000.

    Is there a fix for this?
    Cheers!

  • Lets try to convert 3500 euro to roubles. the result is 139�250.356 Russian rubles. What is � in result and how to fix it?

  • Hi nice effort on php , I make an update on C#.net for Asp.Net developers , it just need three arguments and will give you the converted amount

    http://umairaslam.blogspot.com/2012/01/google-currency-converter-code.html

  • Same prob with me
    I think ajax not returning proper html value for ” , ” .

    302 U.S. dollars = 15�624.1916 Indian rupees

  • In so far as Davids comment :

    “PHP Parse error: syntax error, unexpected ‘;’ in /home/forumed/public_html/counter/currency/convert.php(39) : eval()’d code on line 1”

    Find all instances of “&amp;” in the code and replace with simply “&” and all will work fine.

    Thank you Zvonko!

  • as for the other error concerning � –

    What you need to do is use

    echo utf8_encode($x[‘lhs’] . ‘ = ‘ . $x[‘rhs’]);

    in place of

    echo $x[‘lhs’] . ‘ = ‘ . $x[‘rhs’];

    on line 39