I've been writing a currency converter and need to use jQuery and AJAX to send the to and from currencies, and the value to convert to a PHP files, which will return the converted value.
My solution is based off of: How can I call PHP functions by JavaScript? however it doesn't seem to work.
jQuery code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
function exchange(from, to, amount){
alert("got to here"); //this alert shows
jQuery.ajax({
type: "POST",
url: 'exchange_caller.php',
dataType: 'json',
data: {functionname: 'exchange_rate_convert', arguments:["USD", "EUR", 1]},
//dummy pass values
success: function (obj, textstatus){
if( !('error' in obj)){
answer = obj.result;
alert(answer); //neither of these alerts show
alert('anything');
}
else{
console.log(obj.error);
alert("got an error"); //this alert doesn't show
}
}
});
alert("passed the block"); //this alert shows
return false; //return false so the page doesn't refresh
}</script>
The code in the php file 'exchange_caller.php' (set up as a dummy).
<?php header('Content-Type: application/json');
$aResult = array();
if(!isset($_POST['functionname'])){
$aResult['error'] = 'No function name!';
}
if(!isset($_POST['arguments'])){
$aResult['error'] = 'No function arguments';
}
if(!isset($aResult['error'])){
switch($_POST['functionname']){
case 'exchange_rate_convert':
if(!is_array($_POST['arguments']) || (count($_POST['arguments']) < 3)){
$aResult['error'] = 'Error in arguments!';
}
else{
$aResult['result'] = exchange_rate_convert($_POST['arguments'][0], $_POST['arguments'][1], $_POST['arguments'][2]);
}
break;
default:
$aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
break;
}
}
echo json_encode($aResult);
function exchange_rate_convert($from, $to, $amount){ //function to run
//dummy code, just return 2 for now
$value = 2;
return $value;
}?>
When this runs I receive the 'got to here' and 'passed the block' error messages, but neither of the messages when I should be getting a result back.
Any help would be greatly appreciated.
Thank you.