I am sending two variables to my php page for calculation then echoing the end result back. My response text always equals one.
The Javascript:
var xhttp = new XMLHttpRequest();
xhttp.open("GET","calc.php?w1="+ftest+"&w2="+ltest,true);
xhttp.onreadystatechange = function() {
if(xhttp.readyState==4)
{
var dog = xhttp.responseText;
alert(dog);
}
};
xhttp.send(null);
}
The php:
I set the end var to a random number here just to test if my math was causing the problem.
$startdate = $_GET['w1'];
$endDate = $_GET['w2'];
$workingdays = 239;
echo $workingDays;
Set $workingDays
directly to 10
( random number ). If it is not 10, then you are clearly not seeing the result of that echo statement.
1
is often used as the output to native PHP functions such as isset
You're case is wrong.
$workingdays = 239;
echo $workingDays;
Make it workingDays (with capital D) in both places.
Always use isset()
for receiving data and you are using variable $workingdays
for declaration and for echo $workingDays
, take care of these things. I hope this will work for you.
$startdate = '';
$endDate ='';
if(isset($_GET['w1']))
{
$startdate = $_GET['w1'];
}
if(isset($_GET['w2']))
{
$endDate = $_GET['w2'];
}
$workingdays = 239;
echo $workingdays;
die;
Try adding this variable in your ajax code just to make a test if in the server side is receiving the data you sent using get method.
var ftest = 1;
var ltest = 2;
I assumed that your ajax code is inside the a function let say myfunction
and you have a link like this <a href="#" onclick="myfunction()">link</a>
Here is the full implementation of the code assuming that your filename is index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax</title>
</head>
<body>
<a href="#" onclick="myfunction()">link</a>
<script type="text/javascript">
function myfunction () {
var ftest = 1;
var ltest = 2;
var xhttp = new XMLHttpRequest();
xhttp.open("GET","calc.php?w1="+ftest+"&w2="+ltest,true);
xhttp.onreadystatechange = function() {
if(xhttp.readyState==4) {
var dog = xhttp.responseText;
alert(dog);
}
};
xhttp.send(null);
}
</script>
</body>
</html>
and Calc.php
<?php
$startdate = $_GET['w1'];
$endDate = $_GET['w2'];
$workingdays = 239;
$result = $startdate + $endDate;
echo "$result";
?>
In this example you alert will equal to 3 it be same in your code
Hope this will help