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);
I'm programming appointment planer and still struggling with the issue that javascript doesn't generate events and prints the code just in plain text, so at first I have one php function which fetches all appointments from the sql database and generates javascript code
<script>
function getEventData() {
<?php
function showAppointments($von, $bis){
$link = OpenDB();
try {
$query = 'SELECT termin_id, client, dateFrom, dateTill, title, descri FROM termin WHERE dateFrom BETWEEN :von AND :bis';
$statement = $link->prepare($query);
$statement->bindValue(':von', $von, PDO::PARAM_STR);
$statement->bindValue(':bis', $bis, PDO::PARAM_STR);
$statement->execute();
$row = $statement->fetchAll();
}
catch (PDOException $e) {
p($e);
}
CloseDB($link);
return $row;
}
if(empty($von) && empty($bis)) {
$von = date("Y.m.j",strtotime("monday this week"));
$bis = date("Y.m.j",strtotime("sunday this week"));
}
if(isset($_POST['last_week'])){
$von = date("Y.m.j",strtotime("previous monday"));
$bis = date("Y.m.j",strtotime("previous sunday"));
}
if(isset($_POST['next_week'])){
$von = date("Y.m.j",strtotime("next monday"));
$bis = date("Y.m.j",strtotime("next sunday"));
}
$rows = showAppointments($von, $bis);
echo "const appointments = [";
for($i = 0; $i < sizeof($rows); $i++) {
$columns = array_values($rows[$i]);
echo "[";
for($j=0; $j< sizeof($columns); $j++){
echo "'".$columns[$j]."'";
if( $j < sizeof($columns)-1) echo ",";
}
echo "]";
if( $i < sizeof($rows)-1) echo ",";
}
echo "];";
?>
then all events are generated by jquery and returned
return {
events:[
$.each(appointments, function(index, row){
eval("{'id':"+ row[0] + ",'client':"+ row[1] +",'start':" + new Date(row[2])+",'end': "+ new Date(row[3]) +",'title':'"+ row[4] +"','description':'"+ row[5] +"'}");
});
]}}
</script>
the code in foreach is printed as plain text, how can I fix the issue? it should actually print something like
{'id':1, 'start': new Date(year, month, day, 12), 'end': new Date(year, month, day, 13, 30),'title':'Lunch with Mike'}
you should try the Jquery.each outside Events and then use eval(Array.join); in JavaScript, that should work
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>
i make a sql query asking for data(its a text question), i output the (question) with a checkbox to the left of it and an input field underneath it to give point worth to it(like a teacher making an exam) . All in a loop w arrays. It outputs the correctly checked questions but only will assign point values to first three questions if there checked. so if i check q1 q2 and q4 it will output q1 q2 q4 and q1 points q2points. Thats my problem, I only want to be able to select three total questions and assign those questions their points.
php in the html
$sql = " SELECT Question FROM examQuestions";
$result = mysqli_query($dbCon, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<input type="checkbox" name="checkboxvar[]" value="'.$row["Question"].'">'.$row["Question"].'<input placeholder="10" class="form-control" type="number" name="points[]">'."<br />";
}
}
im trying to output the data using this:
$checkboxvar = $_POST['checkboxvar'];
$examName = $_POST['examName'];
$questionWorth = $_POST['points'];
$i=1;
$total = 0;
while ($i < 4) {
$x = $i - 1;
echo $checkboxvar[$x];
echo $questionWorth[$x]."<br />";
$total = $total + $questionWorth[$x];
$i = $i +1;
}
echo $total;
As I told you in the comments try modifying your code like this:
$sql = " SELECT Question FROM examQuestions";
$result = mysqli_query($dbCon, $sql);
$i = 0;
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<input type="checkbox" name="checkboxvar[]" value="'.$i++.'-'.$row["Question"].'">'.$row["Question"].'<input placeholder="10" class="form-control" type="number" name="points[]">'."<br />";
}
}
And then, to have the right points for the correspondig question something like this:
$checkboxvar = $_POST['checkboxvar'];
$examName = $_POST['examName'];
$questionWorth = $_POST['points'];
$i = 0;
$total = 0;
while ($i < 3) {
$question = explode("-", $checkboxvar[$i]);
echo $question[1];
echo $questionWorth[$question[0]]."<br />";
$total += $questionWorth[$question[0]];
$i++;
}
echo $total;
This should do the work.
If i understand your implied question correctly, you will need some client side (javascript) code that keeps track of the number of checked checkboxes. As soon as one checks three boxes all remaining ones and corresponding text boxes are disabled.
for naive vanilla js solution your php could look like this:
$index = 0;
while($row = mysqli_fetch_assoc($result)) {
echo "<label><input class='questions' type='checkbox' name='question_{$index}' value='{$row["Question"]}' on_change='limit_to_three(this);'>{$row["Question"]}<label><br>";
echo "<input class='scores' name='score_{$index}'><br>";
$index++;
}
For modern browsers you would need the following in your javascript :
var selected_count = 0;
function limit_to_three(selected_checkbox) {
if (selected_checkbox.checked) {
selected_count++;
} else {
selected_count--;
}
var limit_reached = (selected_count == 3);
var checkboxes = document.getElementsByClassName('questions');
var scores = document.getElementsByClassName('scores');
for (var i=0; i<checkboxes.length; i++) {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = scores[i].disabled = limit_reached;
}
}
}
Now, upon submit, you can assume that only checked question checkboxes will be submitted, so your php code could be like this:
$total = 0;
$length = strlen('questions_');
foreach ($_POST as $name => $value) {
if (substr($name, 0, $length) == 'questions_') {
$index = substr($name, $length - strlen($name));
echo $_POST[$name];
echo "<br>";
echo $_POST["scores_{$index}"];
$total += $_POST["scores_{$index}"];
}
}
As i said, this is a naive implementation, that sends question texts back and forth. If i were you i would add ID column to your questions table and use it instead of dynamically generated indexes
Then your html could be generated like this:
while($row = mysqli_fetch_assoc($result)) {
echo "<label><input class='questions' type='checkbox' name='question_{$index}' value='{$row["ID"]}' on_change='limit_to_three(this);'>{$row["Question"]}<label><br>";
echo "<input class='scores' name='score_{$row["ID"]}'><br>";
}
and your receiving php could be like this:
$checked = explode(',', $_POST['questions']);
for ($checked as $id) {
$total += $_POST["scores_{$id}"];
}
Also you could retrieve the checked questions by
$sql = "SELECT * FROM Questions WHERE ID IN ({$_POST['questions']})";