Saturday, February 4, 2012

Currency converter for php

  1. Create html element for calling ajax function
  2. create currency.js and add code
    1. function currency(amount){

       //Get all the values

       var from = "USD";
       var to = $('#convert').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').hide();

       //Put received response into result div
       $('#results').html(data);
          if(document.getElementById('currency_converter_result'))
          {
                  $('#results').html($('#currency_converter_result').find('span').html());
                  $('#results').show();
          }
       }

       });
       };
  3. create ajax_converter.php for calling api
    1. $amount = $_POST['amount'];
      $from =$_POST['from'];
      $to = $_POST['to'];
      //make string to be put in API
      $string = $amount.$from."=?".$to;

      //Call Google API
      //$google_url = "http://www.google.com/ig/calculator?hl=en&q=".$string;
      $google_url = "http://www.google.com/finance/converter?a=".$amount."&from=USD&to=".$to."";


      //Get and Store API results into a variable
      //$result = file_get_contents($google_url);
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $google_url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
      curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
      $result = curl_exec ($ch);
      curl_close ($ch);
             
      var_dump($result);


enjoy :D

No comments:

Post a Comment