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;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
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:
Then in jQuery load the response