Ajax response text is always 1 - javascript

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 link
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>
link
<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

Related

How to periodically fetch data from psql table

I am fetching data from a psql table and passing it to javascript as json array for display as a time series chart. The data passed needs to be in the from of an array.
As the data in the table is updated periodically, I need to constantly fetch the data from psql e.g. every 15 minutes and pass updated array to javascript.
I search but so far I couldn't any solution. My question is how can I fetch data from psql periodically.
Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<script>
var Device_Data;
var time, batt;
var timeArray = [];
var battArray = [];
var N = 12;
for (i = 0; i < N; i++) {
timeArray.push(0);
battArray.push(0); }
function dspChrt(Device_Data) {
console.log(Device_Data[0].date_time);
console.log(Device_Data[1].battery_voltage_mv);
time = Device_Data[0].date_time;
batt = Device_Data[1].battery_voltage_mv;
timeArray.shift();
timeArray.push(time);
battArray.shift();
battArray.push(batt);
</script>
</head>
<body>
<?php
require("Connection.php");
$stmt = $conn->prepare("Select date_time, battery_voltage_mv FROM measuring_device_statuses order by date_time desc limit 12");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$WData = $stmt->fetchAll();
/*
echo "<pre>".print_r($WData, true)."</pre>";
die();
*/
?>
<script>
var WData = <?php print_r(json_encode($WData));?>;
//console.log(WData);
dspChrt(WData);
</script>
</body>
</html>
Keep you data fetch php script in some file "fetch.php" and through javascript set interval function call it periodically for example this code prints alert every 3 secs.
setInterval(function(){ alert("Hello"); }, 3000);
You can use AJAX for this purpose.
HTML
<div id="myDiv"></div>
JavaScript
<script>
window.onload = function(){
loadDoc();
SetInverval(loadDoc, (10000 * 60 * 15)); // Perform function every fifteen minutes
}
function loadDoc() {
var div = document.getElementById("myDiv"); // Get Div
div.innerHTML = ""; // Set to nothing
var xhttp = new XMLHttpRequest(); // Create new XML object
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) { // If successful
div.innerHTML = this.responseText; // Display result
}
};
xhttp.open("GET", "loadDoc.php", true);
xhttp.send();
}
This should be in your PHP file, named loadDoc.php or whatever you choose to replace it to.
<?php
require("Connection.php");
$stmt = $conn->prepare("SELECT date_time, battery_voltage_mv FROM measuring_device_statuses ORDER BY date_time DESC LIMIT 12");
$stmt->execute();
//$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$WData = $stmt->fetchAll();
$stmt->close();
echo "<pre>".print_r($WData, true)."</pre>";
die();
?>

Ajax - Issue - Sending JavaScript Var to PHP script

I have not been able to find a simple example of ajax with single variable, everything on here is made way too complicated for an AJAX beginner. I've watched about 4 different YouTube videos on the topic, but can't seem to get it right.
I have the src of an image in a variable like so with a JavaScript..
<img alt="" src="blah.jpg" style="height: 276px; width: 200px" id="imgClickAndChange1" onclick="changeImage(this)" />
<script language="javascript">
function changeImage(imagePass) {
var num = Math.floor((Math.random() * 48) + 1);
var n = num.toString();
var numImg = n.concat(".jpeg");
var string = "/Images/Folder/"
var final = string.concat(numImg);
imagePass.src = final;
//(this is where I want to pass the variable imagePass.src or "final" to a php script w/ Ajax)
Here is my php script:
<?php>
include_once "code.php"; //connecting to database
$s = (this is where I want the variable to be posted);
$temp = explode('/', $s);
$temp2 = explode('.', $temp[count($temp) - 1]); //this is getting the variable I want from the variable sent(which is actually a number)
$float = (int)$temp2; //changing the number (which is a string) to an int
mysql_query("UPDATE Variable SET `upVote` = `upVote`+1 WHERE id= (variable here)) " //Making a row in my database w/ the id of the variable add 1 to the count
?>
How would I go about posting and sending this w/out a page refresh? AJAX is really confusing me so a working implementation to get me started on this would be great, Thanks a lot.
//Let's just assume the php page where the script is located is called 'hello.php'
To use ajax, try this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function changeImage(imagePass) {
var num = Math.floor((Math.random() * 48) + 1);
var n = num.toString();
var numImg = n.concat(".jpeg");
var string = "/Images/Folder/"
var final = string.concat(numImg);
imagePass.src = final;
$.ajax({
url : 'hello.php',
type: 'post',
data : {'final':final},
success: function()
{
alert('Success!');
}
});
}
</script>
PHP script (hello.php):
<?php>
include_once "code.php"; //connecting to database
$s = $_POST['final'];
$temp = explode('/', $s);
$temp2 = explode('.', $temp[count($temp) - 1]); //this is getting the variable I want from the variable sent(which is actually a number)
$float = (int)$temp2; //changing the number (which is a string) to an int
mysql_query("UPDATE Variable SET `upVote` = `upVote`+1 WHERE id= (variable here)) " //Making a row in my database w/ the id of the variable add 1 to the count
?>

javascript variable into php that is already into javascript

i have tried this code:
<script type="text/javascript">
var s = 0;
document.getElementById('text').value = "<?php echo phpVal[s];?>";
</script>
the problem is how can i put the (s) value into (PHP) code.
Here's more context:
<head>
<?php $s = ["a","b","c"]; ?>
<script type="text/javascript">
function doFun(ss){
var data = "<?php echo json_encode($s); ?>";
document.getElementById('t').value = s[ss];
}
</script>
</head>
<body>
<input type="text" id="t" name="t" />
<button type="button" id="b" name="b" onclick="doFun(0)">doFun</button>
</body>
You can't, by the time s has a value (on the client), the PHP code (on the server) has long-since completed.
What you do instead depends a lot on what your end goal is. You have a lot of options. Here are two of them:
Output the entire phpVal array/object to the client, and then index into it with s.
var s = 0;
var data = <?php echo json_encode(phpVal)%>;
document.getElementById('text').value = data[s];
Send s to the server via ajax, have the PHP code that runs in response to that request pick out the correct value from phpVal, and return that as the result of the ajax, putting it in the client-side input's value. For example:
JavaScript:
var s = 0;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById('text').value = xhr.responseText;
}
};
xhr.open("get-value.php?s=" + encodeURIComponent(s));
// You don't really need this ^
// for `0`, but many times when sending variables to the
// server, you do
xhr.send();
PHP for get-value.php (roughly):
<?php
header('Content-Type: text/plain');
$phpVal = /*...get the value however it is you do that...*/
echo $phpVal[$_GET['s']];
?>
But again it depends on what you're actually trying to do.

I am unable to pass on the value to a PHP script from a javascript using JSON

What is it that I am doing wrong? the value of myid1 is not being accepted by my PHP script. My Javascript code is below followed by my PHP script. Please help.
Javascript code
function generaterepno(selectedid) {
var idnum=selectedid;
var idnum1=idnum.split(":",1);
var text='[{"myid1":idnum1}]';
var httpc = new XMLHttpRequest();
var url = "reportnumber.php";
httpc.open("POST", url, true); // sending as POST
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.setRequestHeader("Content-Length", text.length);
httpc.onreadystatechange = function() {
if(httpc.readyState == 4 && httpc.status == 200) {
alert(httpc.responseText);
var myArr = JSON.parse(httpc.responseText);
}
httpc.send(text);
document.getElementById('genno').value=idnum1;
}
My PHP is as follows-
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$mynewid=$_POST["myid1"];
$mynewid=strip_tags($mynewid);
include("inc_con.php");
$myquery="SELECT MAX(report_number) AS mrepno FROM childreports WHERE child_id='$mynewid' ORDER BY report_number";
$myresult=mysql_query($myquery);
if(!$myresult) {
$outp = '[{"reportn":"0"}]';
echo ($outp);
die('records do not exist');
}
$outp = "[";
while($rm = mysql_fetch_array($myresult)) {
$outp .= '{"reportn":"'.$rm["mrepno"].'"}';
}
$outp .="]";
mysql_close($con);
echo ($outp);
?>
I am a newbie to JSON and Javascript. Been trying to learn it on my own by reading. The alert message of the responseText is displaying a notice that myid1 is not defined. Also in my Javascript the HTML id genno is supposed to get the the return value from PHP code that is the max report number as obtained from the SQL query. Once I get reportn variable with some value I can JSON parse it and put it in the genno id but my problem is sending the myid1 value properly to my PHP script reportnumber.php.
Can someone help please? Thanks!
After prompt and great help from Kyle I made some changes in my Javascript function as follows and my query appears in the comments section below.
function myFunction(arr) {
var tempans = arr.reportn;
var myans = 0;
if(tempans.length == 0) {
var asknum = prompt('Enter previous report number:');
myans = parseInt(asknum)+1;
} else {
myans = parseInt(tempans)+1;
}
document.getElementById('genno').value=myans;
}
Why am i prompted TWICE for a user input?
You have a problem here. var text='[{"myid1":idnum1}]'; is not valid JSON because you're trying to put the variable idnum1 inside the string. It would be easier to set it in an object and then use JSON.stringify() to convert it to JSON.
var text = JSON.stringify({"myid1": idnum1});
In PHP, you then need to decode it from the request body as it won't be set in $_POST.
$contents = json_decode(file_get_contents("php://input"), true);
$myNewId = $contents['myid1'];

calling a function with arguement as a string not working

This is part of my code to display an album on my page. If I call the function like this
<?php
for ($key_Number = 0; $key_Number < count($album); $key_Number++) {
echo 'Gallery1<br>';
}
?>
<script type="text/javascript">ajax_json_gallery('gallery1');</script>
It works fine. gallery1 is a file on my server with test photos inside. If I call it like this
<?php
for ($key_Number = 0; $key_Number < count($album); $key_Number++) {
echo ''.$album[$key_Number].'<br>';
}
?>
<script type="text/javascript">ajax_json_gallery($album[$key_Number]);</script>
It doesn't work. What am I doing wrong? Any ideas?
I need to pass different strings depending on the user so I need to give it a variable.
And yes, my array $album does contain the correct file folder names.
Here is the function that is called.
<script type="text/javascript">
function ajax_json_gallery(folder){
var thumbnailbox = document.getElementById("thumbnailbox");
var pictureframe = document.getElementById("pictureframe");
var hr = new XMLHttpRequest();
hr.open("POST", "json_gallery_data2.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var d = JSON.parse(hr.responseText);
pictureframe.innerHTML = "<img src='"+d.img1.src+"'>";
thumbnailbox.innerHTML = "";
for(var o in d){
if(d[o].src){
thumbnailbox.innerHTML += '<div onclick="putinframe(\''+d[o].src+'\')"><img src="'+d[o].src+'"></div>';
}
}
}
}
hr.send("folder="+folder);
thumbnailbox.innerHTML = "requesting...";
}
function putinframe(src){
var pictureframe = document.getElementById("pictureframe");
pictureframe.innerHTML = '<img src="'+src+'">';
}
And here is the page that gets the photos json_gallery_data2.php
<?php
header("Content-Type: application/json");
$folder = $_POST["folder"];
$jsonData = '{';
$dir = $folder."/";
$dirHandle = opendir($dir);
$i = 0;
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && preg_match("/.jpg|.gif|.png/i", $file)){
$i++;
$src = "$dir$file";
$jsonData .= '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
}
}
closedir($dirHandle);
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
?>
This is mixing server-side and client-side code:
ajax_json_gallery($album[$key_Number]);
The variables $album and $key_number aren't defined in JavaScript, so it can't use them. (I'm sure when it's "not working" it's actually telling you on the JavaScript console that those variables aren't defined.)
To emit values from PHP, you need to surround them with <?php ?> tags. Additionally, since it's a string in JavaScript, it needs to be enclosed in quotes in the JavaScript. Something like this:
ajax_json_gallery('<?php echo $album[$key_Number]; ?>');
1st:
$key_Number varibale on your server in the line:
<script type="text/javascript">ajax_json_gallery($album[$key_Number]);</script>
Contains count($album) value, which not exists in the array.
2nd:
If you trying to output php value in this line:
<script type="text/javascript">ajax_json_gallery($album[$key_Number]);</script>
Then try to enclose output in <?php ?> tags:
<script type="text/javascript">ajax_json_gallery('<?php echo $album[$key_Number]; ?>');</script>
3rd:
Single quotes does not allow to parse variables in string.
echo ''.$album[$key_Number].'<br>';
This ^ line doing not what you expecting.
Try to use double quotes:
echo "{$album[$key_Number]}<br>";

Categories

Resources