So, basically i'm trying to create a simple usd
to pounds
converter using php and ajax. I know it'd be much easier with jQuery but this is an assignment and jQuery isn't allowed. Below is the code i'm working on, but when I run it gives me "Please make sure entry is a valid number." even when i'm definitely putting in a numeric value. I've been searching for hours to try to find out how to fix this code, so i'm hoping someone here can give me some insight.
HTML
<form method="get" action="">
<label for="damount">Dollars to Convert:</label>
<input type="text" name="damount" id="damount">
<div>
<input type="button"value="go" onclick="submitForm();">
</div>
<p id="results"></p>
</div>
</form>
AJAX
var http2 = createRequestObject();
function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
function submitForm() {
http2.open('get', 'calculations.php');
http2.onreadystatechange = toCalc;
http2.send(null);
}
function toCalc() {
if(http2.readyState == 4){
document.getElementById("results").innerHTML = http2.responseText;
}
}
PHP
if (isset($_REQUEST['damount']) && is_Numeric($amount))
{
$rate = 0.80;
$amount = $_REQUEST['damount'];
$money = $rate * $amount;
echo '£' . number_format($money, 2, '.', '');
}
else
{
echo "Please make sure entry is a valid number.";
}
I'm still really new to aJax, so any help would be appreciated.
The problem is in ajax you have to pass the value $_REQUEST['damount'].As you are doing a get request you should pass it as query string.
function submitForm() {
var amount = document.getElementById("damount").value;
http2.open('get', 'calculations.php?damount=' + amount);
http2.onreadystatechange = toCalc;
http2.send(null);
}
The problem is causing because you are sending a GET http request to the server and but you are not sending the data to the server. You have to use query string to pass the data to the server while calling the function.
In Ajax file do changes
function submitForm() {
damount = document.getElementById("damount").value;
http2.open('get', 'calculations.php?damount=' + damount);
http2.onreadystatechange = toCalc;
http2.send(null);
}
In php file now damount will be available. Here in php file $amount variable is undefined in is_numeric function. Because it has defined inside the block later of condition check. So do changes
<?php
if (isset($_REQUEST['damount']) && is_Numeric($_REQUEST['damount']))
{
$amount = $_REQUEST['damount'];
$rate = 0.80;
$money = $rate * $amount;
echo '£' . number_format($money, 2, '.', '');
}
else
{
echo "Please make sure entry is a valid number.";
}
?>