0

so i'm currently trying to implement a currency conversion script using Jquery, curl, ajax and Google api, however I'm having some problems.

So here is the jquery + ajax

$(document).ready(function() {

    $("#convert").click(function () {
                var from = $("#from").val();
                var to = $("#to").val();
                var amount = $("#amount").val();

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

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

           success: function(data){

           $('#result').show();

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

And here is what i have in conversion.php

<?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'];

Now the problem is when i click the convert button it is outputting the whole webpage in the #results div rather than $x from conversion.php

I've spent all day on this now so any help is greatly appreciated.

FYI - Curl is installed and working correctly

3
  • What do you mean by stating "outputting the whole webpage"? Is it the contents of conversion.php file itself? You can also try the url "conversion.php" (along with params) from your browser or from curl command line to see if that works correctly. Commented Jan 28, 2012 at 17:33
  • Sorry, i am referring to the webpage which I am testing the script on, so in #result it displays the whole webpage (header, nav menu, content etc). Commented Jan 28, 2012 at 17:40
  • Try console.log(data) inside your success function. Check in your Browser debugger (like Firebug) to see what is the POST request sent and response received from the server. That will probably help. Commented Jan 28, 2012 at 17:49

4 Answers 4

1

Well I'm not sure if this is an ussue, but the way you construct the URL to call for data is incorrect. What you have is

$url = 'http://www.google.com/ig/calculator?hl=en&amp;amp;q=' . $encoded_string;

This is not correct. Note &amp;q part. You need to change your code as follows:

$url = 'http://www.google.com/ig/calculator?hl=en&q=' . $encoded_string;
Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately that didn't fix it, but well spotted all the same :-)
0

Can't say for sure but I don't see why your are echoing eval($out . ';')? Only call eval without the echo.

The reason for using php to make this call to google is due to cross domain restrictions. But given that you are loading the json response in your server you could return the json response straight back to jQuery. No need to parse it on the server. Try this and let us know if it works:

<?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);

header('Content-type: application/json');
echo $results;
// this should output the same data google sent, which is now in your domain so you get no cross domain errors

Then in jQuery load the response

$.ajax({
       type: "POST",
       url: "conversion.php",
       data: dataString,
       dataType:"json",
       success: function(data){
            // If I load this page http://www.google.com/ig/calculator?hl=en&q=1USD=?EUR   
            // I get {lhs: "1 U.S. dollar",rhs: "0.757174226 Euros",error: "",icc: true}
            // Assuming your call is correct and you have the same response you can now 
            // access the data like so:


       $('#result').show();

        //Put received response into result div
        $('#result').html(data.lhs + ' is equivalent to ' + data.rhs + ' Today');
       }
     });

2 Comments

Thanks for your response Juank, unfortunately that didn't produce any result.
is the success callback firing in the ajax call? if so, what are you getting in the data variable?
0

I fixed the following and it works for me on XAMPP 1.7.7 with curl extension enabled.

Change your query to

$url = 'http://www.google.com/ig/calculator?hl=en&q=' . $encoded_string;

Use quotes for every key.

if (!$comment)
{
    if ($results[$i] == '{')         $out .= ' array(\'';
    else if ($results[$i] == '}')    $out .= ')';
    else if ($results[$i] == ',')    $out .= ',\'';
    else if ($results[$i] == ':')    $out .= '\'=>';
    else                             $out .= $results[$i];
}

Prevent the default action if #convert is a form submit button.

$("#convert").click(function (event) {
    event.preventDefault();
    var from = $("#from").val();
    // ...
});

Now posting amount=3&from=EUR&to=USD returns 3 Euros = 3.9792 U.S. dollars.

Comments

0

I'm new to stackoverflow, so don't know yet when to best use comments, new answers..

but in the meantime after deep research I found a very simple PHP currency converting script at: http://www.expertcore.org/viewtopic.php?f=67&t=2161

This is actually exactly what I was looking for, very light and perfectly fits the needs of my project... maybe it helps someone else, too...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.