Why is my PHP array not posting as an array to JavaScript? - javascript

This is my first time building my own JavaScript code so not completely up to speed with it yet.
I am querying my MySQL database to get all the disabled days so that the results are disabled in the date picker. I nearly have this working but the problem is that only one set of values is being posted to the JavaScript variable when there are two being read from the database. i.e if there are two bookings in my database, one from 6/3/15 - 10/3/15 and one from 14/3/15 - 17/3/15 only one is being stored in the JavaScript variable. i.e 6/3/15 - 10/3/15.
When I echo the json_encode($date_list) i get the results as:
["2015-3-14","2015-3-15","2015-3-16","2015-3-17","2015-3-17"]
["2015-3-6","2015-3-7","2015-3-8","2015-3-9","2015-3-10","2015-3-10"]
Which is correct but when I do a console.log on the bookedDays variable the only values stored are:
["2015-3-6", "2015-3-7", "2015-3-8", "2015-3-9", "2015-3-10", "2015-3-10"]
Below is the code I am using.
<?php
$bookeddates = "SELECT fromdate, todate FROM messages WHERE listing_id = '".$_GET['listingid']."'";
$resultbookeddates = mysql_query($bookeddates) or die(mysql_error() . "<br>" . $bookeddates);
while ($rowbookeddates = mysql_fetch_assoc($resultbookeddates)) {
$from = date('Y-n-j', strtotime($rowbookeddates['fromdate']));
$to = date('Y-n-j', strtotime($rowbookeddates['todate']));
$start_time = strtotime($from);
$end_time = strtotime($to);
$date_list = array($from);
$current_time = $start_time;
while($current_time < $end_time) {
//Add one day
$current_time += 86400;
$date_list[] = date('Y-n-j',$current_time);
}
$date_list[] = $to;
?>
<script type="text/javascript">
var bookedDays = <?php echo json_encode($date_list); ?>;
</script>
<?php
echo json_encode($date_list);
} ?>
Any help would be appreciated.

you need to move your injected JS outside of your while loop like this. As said in comments, build your data first, then output it.
<?php
$bookeddates = "SELECT fromdate, todate FROM messages WHERE listing_id = '".$_GET['listingid']."'";
$resultbookeddates = mysql_query($bookeddates) or die(mysql_error() . "<br>" . $bookeddates);
$date_list = array();
while ($rowbookeddates = mysql_fetch_assoc($resultbookeddates)) {
$from = date('Y-n-j', strtotime($rowbookeddates['fromdate']));
$to = date('Y-n-j', strtotime($rowbookeddates['todate']));
$start_time = strtotime($from);
$end_time = strtotime($to);
$date_list[] = $from;
$current_time = $start_time;
while($current_time < $end_time) {
//Add one day
$current_time += 86400;
$date_list[] = date('Y-n-j',$current_time);
}
$date_list[] = $to;
} ?>
<script type="text/javascript">
var bookedDays = <?php echo json_encode($date_list); ?>;
</script>
<?php
echo json_encode($date_list);

Your problem is the asigment of javascript variable.
Please, move outside the while loop the asigment and you can see all results.
<?php
$bookeddates = "SELECT fromdate, todate FROM messages WHERE listing_id = '".$_GET['listingid']."'";
$resultbookeddates = mysql_query($bookeddates) or die(mysql_error() . "<br>" . $bookeddates);
while ($rowbookeddates = mysql_fetch_assoc($resultbookeddates)) {
$from = date('Y-n-j', strtotime($rowbookeddates['fromdate']));
$to = date('Y-n-j', strtotime($rowbookeddates['todate']));
$start_time = strtotime($from);
$end_time = strtotime($to);
$date_list = array($from);
$current_time = $start_time;
while($current_time < $end_time) {
//Add one day
$current_time += 86400;
$date_list[] = date('Y-n-j',$current_time);
}
$date_list[] = $to;
} ?>
<script type="text/javascript">
var bookedDays = <?php echo json_encode($date_list); ?>;
</script>

Related

How to send php value to javascript with script tag?

php code is
<?php
if (isset($_POST['search']))
{
$startDate = $_POST['start'];
$startDate = str_replace('/', '-', $startDate );
$startDate = date("Y-m-d", strtotime($startDate));
// echo $startDate;
$endDate = $_POST['end'];
$endDate = str_replace('/', '-', $endDate );
$endDate = date("Y-m-d", strtotime($endDate));
// echo $endDate;
$model = $_POST['model'];
// echo $model;
$dates = getDatesStartToLast($startDate, $endDate);
// echo $dates
for ($i=0; $i < count($dates); $i++){
echo "<form method = 'post'>";
echo "<tr>";
echo "<td><button type = 'submit' style = 'border-color : white; background-color : white; outline : 0; border : 0' name = 'datebutton' value = '$model,$dates[$i]'>$dates[$i]</td>";
echo "</form>";
$query = mysqli_query($conn, "SELECT * from elentec_count where Date = '$dates[$i]' and model = '$model'");
$row = mysqli_fetch_row($query);
echo "<td>$row[2]</td><td>$row[3]</td><td>$row[4]</td><td>$row[5]</td><td>$row[6]</td><td>$row[7]</td>";
}
$burrCordResult = updateChart($conn, $model, $dates);
$burrCordResult = ['mon', 'Tue'];
print_r($burrCordResult);
}
?>
<script>var BurrLoc = "<?= $burrCordResult ?>";</script>
javascript code is
console.log(BurrLoc)
The php code is in the middle of the html code. It makes the error
Uncaught ReferenceError: BurrLoc is not defined
I don't know why this matter comes out.
Just do an echo within your script with script tags enclosing it anywhere within your PHP code to send it.
echo "<script>var BurrLoc ='$Burrloc';</script>";

Get JSON Array into another file via Ajax

I'm trying to add a JSON array from a separate file into another array in my main page via Ajax. For some reason my Ajax is not working, There are 4 arrays, I need to store each of them in separate arrays in my main page. This is what I got.
load file:
<?php
session_start();
if(!isset($_SESSION['usersId']))
{
header("Location: ../index.php");
exit();
}
else
{
include_once 'includes/dbh.inc.php';
}
$id = $_SESSION['userId'];
$dBname = "infosensor";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBname);
$sql = "SELECT sensor1, sensor2, sensor3 FROM `$id`;";
$result = mysqli_query($conn, $sql);
$jsonsensor1 = array();
$jsonsensor2 = array();
$jsonsensor3 = array();
$jsonsensorsum = array();
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_assoc($result))
{
$jsonsensor1[] = intval($row['sensor1'] * ($p = pow(10, 2))) / $p;
$jsonsensor2[] = intval($row['sensor2'] * ($p = pow(10, 2))) / $p;
$jsonsensor3[] = intval($row['sensor3'] * ($p = pow(10, 2))) / $p;
$jsonsensorsum[] = intval(($row['sensor1'] + $row['sensor2'] + $row['sensor3']) * ($p = pow(10, 2))) / $p;
}
}
echo json_encode($jsonsensor1);
echo json_encode($jsonsensor2);
echo json_encode($jsonsensor3);
echo json_encode($jsonsensorsum);
?>
Output from the load file:
[5,10,10.99,10.99,13,5,14.31,1,1,5,5,5,1,5,3,3,5,5,1,5,10.32,10.32,5,8,5,10,5,5,19,5,7.36,7.36,5,12.2,12.2,2.2,2.2,23.3,5,10.87,6.87,6.87,5,5,10,10,10,10,5,5,5,5,5,0,5,5]
[8,12.5,12.5,12.53,12.53,8,10.11,1,1,8,8,8,1,8,3,3,8,8,1,8,12.83,32.32,8,8,8,10,8.31,8,10,8,18.2,18.2,8,10.3,10.3,2.29,2.29,12.3,8,8.23,2.23,2.23,8,8,10,10,10,20,5,5,5,5,8,0,8,2]
[6,8.86,8.86,8.87,8.87,6,8.33,1,2,6,2,3,1,6,3,8,6,6,1,6,8.32,7.32,6,8,6,10,3.31,6,12,6,12.3,12.3,6,11.1,11.1,4.09,4.09,33.1,6,5.16,12.16,2.16,6,6,10,20,30,30,30,30,5,0,6,0,6,5]
[19,31.36,32.36,32.4,34.4,19,32.76,3,4,19,15,16,3,19,9,14,19,19,3,19,31.47,49.96,19,24,19,30,16.62,19,41,19,37.86,37.86,19,33.6,33.6,8.6,8.6,68.7,19,24.26,21.26,11.26,19,19,30,40,50,60,40,40,15,10,19,0,19,12]
What I tried in my main page:
$(document).ready(function(){
$.getJSON("loadchart.php", function(jsonsensor1){
var sensor1 = [$jsonsensor1];
var sensor2 = [$jsonsensor2];
var sensor3 = [$jsonsensor3];
var sensorsum = [$jsonsensorsum];
});
});
Don't use multiple encode/echo calls. This will just create invalid json. Instead put your data into a single container(an object or array) and encode echo that.
For instance using a normal array:
$data = [$jsonsensor1,$jsonsensor2,$jsonsensor3,$jsonsensorsum];
echo json_encode($data);
And on the front end access them accordingly
$.getJSON("loadchart.php", function(data){
//get the arrays based on what position you put them
//in the array in the backend
//change this if you end up using a different container,
//eg php associative array or object
var sensor1 = data[0];
var sensor2 = data[1];
//and so on
});
Replace this code :
echo json_encode($jsonsensor1);
echo json_encode($jsonsensor2);
echo json_encode($jsonsensor3);
echo json_encode($jsonsensorsum);
With this code :
$data=array("jsonsensor1"=>$jsonsensor1,"jsonsensor2"=>$jsonsensor2,"jsonsensor3"=>$jsonsensor3,"jsonsensorsum"=>$jsonsensorsum);
echo json_encode($data);

using javascript for loop

I am trying to get the data from database and put it into js for loop
here is the php part:
$result = mysql_query("SELECT * FROM db");
$row = mysql_fetch_array($result);
$array[] = $row['value'];
here is the js part
var days=<?php echo json_encode($row['value']);?>;
for(var i=0;i<days.length;i++){
document.write("Number"+ days[i] +"<br>");
}
When I try to echo the values, I can echo the array in the php part with no problem, but on the js part there is no error, just a blank page
OK whole scenario has changed when viewed the page source
now my code is :
rows = array();
$result = mysql_query("SELECT * FROM db");
$i=1;
while($row = mysql_fetch_array($result)) {
$array[] = $row['value'];
$i++;
}
var days=<?php echo json_encode($array);?>;
for(var i=0;i<days.length;i++){
document.write("Number"+ days[i] +"<br>");
when I viewed the page source I can see the values
var days=["8","11","18"];
Now the next step is to implement it into js graph code
If I try the js code
var days=<?php echo json_encode($array);?>;
for(var i=0;i<days.length;i++){
document.write("Number"+ days[i] +"<br>");
on a seperate page alone it works, but when I put the code in dataPoints
dataPoints: [
{y: var days=<?php echo json_encode($array);?>;
for(var i=0;i<days.length;i++){
document.write(days[i] +"<br>");
};, label: "test"},
]
I get blank page with no error. and still see the values when I view the page source . var days=["8","11","18"];
your page is blank because php return not string json
you can try:
var days= JSON.parse("<?php echo json_encode($row);?>");
for(var i=0;i<days.length;i++){
document.write("Number"+ days[i] +"<br>");
}
Or:
php file:
$result = mysql_query("SELECT * FROM db");
$row = mysql_fetch_array($result);
return json_encode($row);
js file:
$.get("phpfile.php",function(rs){
var days = JSON.parse(rs);
for(var i=0;i<days.length;i++){
document.write("Number"+ days[i] +"<br>");
}
});

Json working for certain vars but not for others

I've made a script that requests information via Json. For some variables this works just fine, for others it doesn't.
When I use alert() for the variable neighbour1 it says the variable is undefined, when doing the same for the variables number and colour it works just fine.
This is the request script:
function getcolours() {
var hr = new XMLHttpRequest();
hr.open("GET", "camp_map_script.php", true);
hr.setRequestHeader("Content-type", "application/json");
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
for (var obj in data) {
number = data[obj].number;
colour = data[obj].colour;
neighbour1 = data[obj].n1;
alert (neighbour1);
window["colour" + number] = colour;
var x = document.getElementsByClassName(number + ' ' + colour);
x[0].style.display = "block";
}
}
}
hr.send(null);
}
This is the php part:
<?php
include_once("../php_includes/check_login_status.php");
?><?php
$number = "";
$sql = "SELECT camp_id FROM users WHERE username='$log_username'";
$query = mysqli_query($connect, $sql);
$row = mysqli_fetch_row($query);
$campid = $row[0];
$sql = "SELECT players FROM campaigns WHERE id='$campid'";
$query = mysqli_query($connect, $sql);
$row = mysqli_fetch_row($query);
$players = $row[0];
$number = ($players*2)-1;
$sql = "SELECT number, colour, player, n1, n2, n3, n4, n5, n6, n7, n8 FROM lands WHERE camp_id='$campid' ORDER BY number";
$query = $connect->query($sql);
$jsonData = '{';
if ($query->num_rows > 0) {
while($row = $query->fetch_assoc()) {
$jsonData .= '"obj'.$row["number"].'":{"number":"'.$row["number"].'", "colour":"'.$row["colour"].'", "player":"'.$row["player"].'", "n1":"'.$row["n1"].'"},';
}
}
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
$connect->close();
?>
Also when I check the php document the variable n1 is echoed correctly. So the error must be on the java script side or the transit.
It is probably something stupid that I'm overlooking but I just don't see it. I've copy pasted the working parts and changed them to work with other variables but it still doesn't work. :/

Div not displaying output which is made hidden by default in css

This is the java script function.I want it to make the div "resultss" visible and show the output.
But it's not displaying results, php code is executed without errors. Whys is this not displaying any output.
I'm trying to append the results at the bottom of same page where user submits some data
<script>
function myFunction()
{
var e = document.getElementById("resultss");
e.style.display = "block";
<?php
$format = $_SESSION["ff"];
$ses_id = $_SESSION["id"];
$filena = $_SESSION["filename"];
//$pubquery = $_SESSION["pubquery"];
$result1 = shell_exec("C:\Python27\python.exe C:\Python27\PredictoR\Model_desc.py $format $ses_id $filena 2>&1");
$properties = explode(" ", $result1);
if($properties[0] == 1)
{
$property = "Substrate";
} else {
$property = "Non-substrate";
}
$molwt = trim(preg_replace('/\s+/', ' ', $properties[1]));
$nhd = trim(preg_replace('/\s+/', ' ', $properties[2]));
$nha = trim(preg_replace('/\s+/', ' ', $properties[3]));
$logp = trim(preg_replace('/\s+/', ' ', $properties[4]));
?>
var molwt = <?php echo json_encode( $molwt); ?>;
var nhd = <?php echo json_encode( $nhd); ?>;
var nha = <?php echo json_encode( $nha); ?>;
var logp = <?php echo json_encode( $logp); ?>;
var property = <?php echo json_encode( $property); ?>;
document.getElementById('properties').innerHTML="Molecule is : "+property+" \n\
<br/>Molecular weight is : "+molwt+" \n\
<br/>No. of hydrogen bond donors = "+nhd+"\n\
<br/>No. of hydrogen bond acceptors = "+nha+"\n\
<br/>Log P : = "+logp+";
}
</script>
Put that PHP code outside javascript function in seperate DIV with id and make this display = none at first then when your showing result call the javascript and you can use display = block or display = inline-block or display = flex (New in CSS3). to make your DIV visible.

Categories

Resources