storing a string from google webapp into an array - javascript

Suppose I would like to create an array on my JS code and push in a string coming from appscript htmlservice. How do I do it? The below does not work.
var array = [];
<? var data = getData(); ?>
<? for (var i = 0; i < data.length; i++) { ?>
<?= array.push(data[i]) ?>
<? } ?>

How about this modification? Please think of this as just one of several possible answers.
Modified script:
var array = [];
<? var data = getData(); ?>
<? for (var i = 0; i < data.length; i++) { ?>
array.push(<?= data[i] ?>); // Modified
<? } ?>
console.log(array);
Reference:
HTML Service: Templated HTML

Related

Changing JSON's HTML table's cell color based on status

I have a HTML table created by JSON. The table is a college semaster's map, it lists all the required courses for your major. I want the courses' cell color depends on the status. For example, green means course is completed, yellow means in progress and red means need to be taken. below is the columns, and createtablefromJSON function
var col2 = ["year","term","major1","major2","major3","major4","major5","core1","Core2","Credits"] ;
function CreateTableFromJSON() {
var myCourses = <?php echo $test1; ?> ;
var col = [] ;// EXTRACT VALUE FOR HTML HEADER.
var col2 = ["year","term","major1","major2","major3","major4","major5","core1","Core2","Credits"] ;
for (var i = 0; i < myCourses.length; i++) {
for (var key in myCourses[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
var table = document.createElement("table"); // CREATE DYNAMIC TABLE.
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col2.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col2[i];
tr.appendChild(th);
}
My question is how to change cell's color based on status of the course
for (var i = 0; i < myCourses.length; i++) {
tr = table.insertRow(-1); // ADD JSON DATA TO THE TABLE AS ROWS.
for (var j = 0; j < col2.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myCourses[i][col[j]];
if (<?php in_array ?> (myCourses[i][col[j]] <?php echo ",". json_encode($done_course) ?> ) {
<?php if ($done) { ?> tabCell.className = 'success'; <?php } ?> }
if (<?php in_array ?> (myCourses[i][col[j]] <?php echo ",". json_encode($pending_course) ?> ) {
<?php if ($pending) { ?> tabCell.className = 'pending'; <?php } ?> }
}
if (<?php in_array ?> (myCourses[i][col[j]] <?php echo ",". json_encode($progess_course) ?> ) {
<?php if ($progess) { ?> tabCell.className = 'inprocess'; <?php } ?> }
}
}
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
you have to check your in array like this,
indexOf()
if (myCourses[i][col[j]] == "<?php echo $done_course; ?>") {
<?php if ($done) { ?> tabCell.className = 'success'; <?php } ?>
}
else if (myCourses[i][col[j]] == "<?php echo $pending_course; ?>") {
<?php if ($pending) { ?> tabCell.className = 'pending'; <?php } ?> }
}
else {
<?php if ($progess) { ?> tabCell.className = 'inprocess'; <?php } ?> }
}
Convert php array to js array. Then use .includes() function to check
for (var i = 0; i < myCourses.length; i++) {
tr = table.insertRow(-1); // ADD JSON DATA TO THE TABLE AS ROWS.
for (var j = 0; j < col2.length; j++) {
var tabCell = tr.insertCell(-1);
var done_course = <?php echo json_encode($done_course); ?> ;
var pending_course = <?php echo json_encode($pending_course); ?> ;
var progress_course = <?php echo json_encode($progress_course); ?> ;
tabCell.innerHTML = myCourses[i][col[j]];
if (done_course.includes(myCourses[i][col[j]])) {
tabCell.className = 'success';
} else if (pending_course.includes(myCourses[i][col[j]])) {
tabCell.className = 'completed'; }
else {
tabCell.className = 'inprocess'; }
}
}

How to fix problem with json_encode() via an xml request

So I have a problem with my Code.
This is my index.html.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div id="container">
</div>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//Nachrichten aus JSON zurueckparsen
var messages = JSON.parse(this.responseText);
//alle Nachrichten durchgehen
messages.forEach(function(message) {
var container = document.getElementById('container');
var messageElement = document.createElement('div');
messageElement.id = 'message'+message.id;
messageElement.innerHTML = message.message;
container.appendChild(messageElement);
//Onclick Handler für die message hinzufügen
messageElement.onclick=function() {
alert('message '+message.id+' clicked');
}
});
}
};
xhttp.open("GET", "login.php", true);
xhttp.send();
</script>
</body>
</html>
And this is my login.php:
<?php
$ar = array();
for ($i = 0; $i < 10; $i++) {
array_push($ar, array("test", "123"));
}
var_dump(json_encode($ar));
?>
So like you see I'm trying to make 10 arrays with the array_push method. But when I open the index it says "undefined" and that 10 times. Please help me.
It says "undefined" because there are no defined keys for "id" and "message" in your response.
You need to set the keys for response. Try this.
<?php
$ar = array();
for ($i = 0; $i < 10; $i++) {
$ar[] = array("id"=>$i, "message"=>"test $i");
}
echo json_encode($ar);
?>
Try this.
In PHP you don't need to use the array_push method to add a new element to the array.
Instead, you use this pattern since PHP extends the array automatically.
$ar[] = [];
<?php
$ar = [];
for ($i = 0; $i < 10; $i++) {
$ar[] = ['test', '123'];
}
var_dump(json_encode($ar));
?>

Using PHP array in the JS code in PDO

I'm trying to use a PHP array in the JS but encountered the error I don't know how to fix.
I was using this example (in my case - it's PDO, not mysqli.): Inserting MYSQL results from PHP into Javascript Array
$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . '; charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$type_zagon = 1;
$id_kurat = 1;
$usid = 78;
$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$num = $stmt1->fetchColumn();
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
$gyvuliu_array = array();
while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
$gyvuliu_array[] = $num;
}
$array_encode = json_encode($gyvuliu_array);
?>
<script>
$('.surinkti_produkcija_paserti_gyvulius').click(function() {
var gyvuliai_fermoje = '<?php echo $array_encode; ?>';
var gyvuliu_array = [1,2,3,4,5,6,7,8,9];
for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
console.log(gyvuliu_array[i]);
}
// DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
});
</script>
I guess something is bad with the $num variable but I'm not sure.
EDIT:
I've changed the second for loop and it looks like it's working:
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
But I'm not sure if it's ok they aren't in the same row.
http://prntscr.com/ft4i9m
EDIT 2 After rickdenhaan's comment, it looks exactly how first for loop. Is it ok? Am I done?
var gyvuliai_fermoje = <?php echo $array_encode; ?>;
You have to remove quotes, why? If you put the value in quotes that mean var gyvuliai_fermoje is a string not an array
Could You please try this once
$stmt1 = $pdo->prepare("SELECT GROUP_CONCAT(num) as nums FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
$row = $stmt1->fetch();
$array_encode = json_encode(explode(",",$row["nums"]));
?>
<script>
var gyvuliai_fermoje = <?php echo $array_encode; ?>;
$('.surinkti_produkcija_paserti_gyvulius').click(function() {
var gyvuliu_array = [1,2,3,4,5,6,7,8,9];
for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
console.log(gyvuliu_array[i]);
}
// DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
});
</script>
Try this
var gyvuliai_fermoje = <?php echo json_encode($array_encode, JSON_HEX_QUOT | JSON_HEX_APOS); ?>;
Problem solved! :) For future visitors, combined all this stuff you guys said, we have this code:
// PDO Connection
$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . ';
charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepared statement with placeholders
$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
// Binding query result to the $num variable (1 is the first column)
$stmt1->bindColumn(1, $num);
// Executing query and replacing placeholders with some variables
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
// Creating a PHP array
$gyvuliu_array = array();
// Fetching through the array and inserting query results using $num variable ((int) makes sure a value is an integer)
while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
$gyvuliu_array[] = (int)$num;
}
// Encoding PHP array so we will be able to use it in the JS code
$array_encode = json_encode($gyvuliu_array);
?>
<script>
var gyvuliai_fermoje = <?php echo $array_encode; ?>;
for (var i = 0; i < gyvuliai_fermoje.length; i++) {
// Stuff you would like to do with this array, access elements using gyvuliai_fermoje[i]
}
</script>
I hope it will help you to understand how to use a PHP array in the JS code in PDO :)

Using PHP to call JS to change HTML table cell values

I'm trying to manipulate my HTML table using datavalues from an SQL database that I'm extracting using PHP.
I've tried a tonne of different ways but I think the best way would be how I am approaching it now, by using a loop to assign an ID tag number corresponding to the Matrix Value of that array.
(EXAMPLE: 11, 12, 13, 21, 22, 23 etc..)
I am then calling a JavaScript function to find the element with that particular ID and replace the value with the SQL Data taken out by the PHP code.
I've inspected the elements on Chrome and can see the data going into the function but the values within the table are staying blank and not being set to the values from the mySQL.
Any help or suggestions will be greatly appreciated.
<?php
$sql = "SELECT * FROM `stock` WHERE 1";
$tableHeader = "<body><center><div><table id=\"infoTable\" class=\"myTable \"><tr><th></th><th> 1 </th><th> 2 </th><th> 3 </th></tr>";
$r_query = mysql_query($sql);
//To Table Details
//prints StackerReclaimer_StatusTable;
include("SR_TableStatus.php");
// output data of each row
echo $tableHeader;
for ($i=1;$i<5;$i++){ //Rows
$row = mysql_fetch_array($r_query);
if($i == 2 || $i==4)
echo"<tr><td> </td></tr>";
echo"<tr><td class = \"leftCol\"> Bed ".($i)."</td>";
for ($j=1;$j<4;$j++){ //Cols
echo"<td bgcolor=\"#E9E6E5\" id =\"$i$j\"></td>";
/***************************************/
$data = strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)";
if( $row["bednumber"] == $i && $row["pilenumber"] == $j ){
// echo"<td bgcolor=\"#E9E6E5\" id = $i$j>".strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)</td>";
echo "<script>swapValue($i$j, ".$data.");</script>";
}
/***************************************/
}
echo"</tr>";
}
echo "</table></div></body></center>";
?>
<!-- This script allows user to click on table rows to direct user to More info for that Coal -->
<script>
function swapValue(var location, var data){
var s = document.getElementById(location);
s.value = data;
}
var table = document.getElementById("infoTable");
if (table != null) {
for (var i = 1; i < table.rows.length; i++) {
for (var j = 1; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
myFunc();
};
}
}
function tableText(tableCell) {
//alert(tableCell.innerHTML);
var Val = tableCell.innerHTML;
Val = Val.substring(0,7);
document.getElementById("searchBox").value = Val;
document.getElementById("searchButton").click();
}
</script>
echo "</table></div></body></center>"
first you did not end the tag properly. you placed out of body
second your block is not even inside body block
so i suggest you rewrite like this
<body>
<div>
<table id="infoTable" class="myTable">
<tr><th></th><th> 1 </th><th> 2 </th><th> 3 </th></tr>
<?php
$sql = "SELECT * FROM `stock` WHERE 1";
$r_query = mysql_query($sql);
//To Table Details
//prints StackerReclaimer_StatusTable;
include("SR_TableStatus.php");
// output data of each row
for ($i=1;$i<5;$i++){ //Rows
$row = mysql_fetch_array($r_query);
if($i == 2 || $i==4)
echo"<tr><td> </td></tr>";
echo"<tr><td class = \"leftCol\"> Bed ".($i)."</td>";
for ($j=1;$j<4;$j++){ //Cols
echo"<td bgcolor=\"#E9E6E5\" id =\"$i$j\"></td>";
/***************************************/
$data = strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)";
if( $row["bednumber"] == $i && $row["pilenumber"] == $j ){
// echo"<td bgcolor=\"#E9E6E5\" id = $i$j>".strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)</td>";
echo "<script>swapValue($i$j, ".$data.");</script>";
}
/***************************************/
}
echo"</tr>";
}
?>
</table>
</div>
<!-- This script allows user to click on table rows to direct user to More info for that Coal -->
<script>
function swapValue(var location, var data){
var s = document.getElementById(location);
s.value = data;
}
var table = document.getElementById("infoTable");
if (table != null) {
for (var i = 1; i < table.rows.length; i++) {
for (var j = 1; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
myFunc();
};
}
}
function tableText(tableCell) {
//alert(tableCell.innerHTML);
var Val = tableCell.innerHTML;
Val = Val.substring(0,7);
document.getElementById("searchBox").value = Val;
document.getElementById("searchButton").click();
}
</script>
</body>
I've found a way to get the outcome needed.
After standing back and taking a break to rest the mind & Eyes, I've came back with fresh eyes and have now solved the issue, i was cluttering up the code by using javascript into the php which just adds to a mess if anyone was to decode or read.
so what the code does is reads values from an SQL database using PHP, reads the bednumber(Location(y)) and pileNumber(location(x))
it then makes the table using the for loops I for Rows and J for Columns,
then each column increment you need to update the SQL Query being sent back with the new cell location $i & $j which are held in the bed and pile number values.
i will post the code that now works, but any suggestions or corrections are gratefully appreciated.
<?php
$tableHeader = "<body><center><div><table id=\"infoTable\" class=\"myTable \"><tr><th></th><th> 1 </th><th> 2 </th><th> 3 </th></tr>";
//prints StackerReclaimer_StatusTable;
include("SR_TableStatus.php");
// output data of each row
echo $tableHeader;
/*####################################*/
for ($i=1;$i<5;$i++){
//$row = mysql_fetch_array($r_query);
if($i == 2 || $i==4)
echo"<tr><td> </td></tr>";
echo"<tr><td class = \"leftCol\"> Bed ".($i)."</td>";
for ($j=1;$j<4;$j++){
$sql = "SELECT * FROM `stock` WHERE `bednumber` = $i AND `pilenumber` = $j";
$r_query = mysql_query($sql);
$row = mysql_fetch_array($r_query); //Creates a loop to loop through results
if( $row["bednumber"] == $i && $row["pilenumber"] == $j ){
echo"<td bgcolor=\"#E9E6E5\">".strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)</td>";
}
else
echo"<td bgcolor=\"#E9E6E5\"> --- </td>";
}
echo"</tr>";
} /*################################*/
echo "</table></div></center></body>";
?>
<!-- This script allows user to click on table rows to direct user to More info for that Coal -->
<script>
var table = document.getElementById("infoTable");
if (table != null) {
for (var i = 1; i < table.rows.length; i++) {
for (var j = 1; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
};
}
}
function tableText(tableCell) {
//alert(tableCell.innerHTML);
var Val = tableCell.innerHTML;
Val = Val.substring(0,7);
document.getElementById("searchBox").value = Val;
document.getElementById("searchButton").click();
}
</script>

Third dropdown populated based from second and first dropdown selections

I am creating an internal web tool that inserts data into a database. I was trying to find out how to create a three-tier dropdown selection, where I would insert the third dropdown's value into the DB.
I stumbled across this answer here:
Populate another select dropdown from database based on dropdown selection
But was done as a two tier dropdown.
My php code is this:
<?php
require 'connect.php';
$query = "SELECT customer_id,customer FROM schema.customer";
$result = $DB_con->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$categories[] = array("customer_id" => $row['customer_id'], "customer" => $row['customer']);
}
$query = "SELECT contract_id, customer_id, contract FROM schema.contract";
$result = $DB_con->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$subcats[$row['customer_id']][] = array("contract_id" => $row['contract_id'], "contract" => $row['contract']);
}
// Third dropdown which isn't originally included with the previous answer
$query = "SELECT subcontract_id, contract_id, subcontract FROM schema.subcontract";
$result = $DB_con->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$subsubcats[$row['contract_id']][] = array("subcontract_id" => $row['subcontract_id'], "subcontract" => $row['subcontract']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
$jsonSubSubCats = json_encode($subsubcats);
?>
Now, the given answer was this:
<head>
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
//Below wasn't part of the answer
echo "var subsubcats = $jsonSubSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].customer,categories[i].customer_id);
}
}
function updateSubCats(){
var catSelect = this;
var customer_id = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[customer_id].length; i++){
subcatSelect.options[i] = new Option(subcats[customer_id][i].contract,subcats[customer_id][i].contract_id);
}
}
</script>
</head>
<body onload='loadCategories()'>
<select id='categoriesSelect'>
</select>
<select id='subcatsSelect'>
</select>
</body>
</html>
But I needed help with the third tier options based from the second dropdown selection. Thanks in Advance. :)
Was able to figure it out.
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
echo "var subsubcats = $jsonSubSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].customer,categories[i].customer_id);
}
}
function updateSubCats(){
var customer_id = this.value;
var subcatSelect = document.getElementById("subcatsSelect")
subcatSelect.onchange = updateSubSubCats;;
for(var i = 0; i < subcats[customer_id].length; i++){
subcatSelect.options[i] = new Option(subcats[customer_id][i].contract,subcats[customer_id][i].contract_id);
}
}
function updateSubSubCats(){
var subsubcatSelect = this;
var contract_id = this.value;
var subsubcatSelect = document.getElementById("subsubcatsSelect");
subsubcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subsubcats[contract_id].length; i++){
subsubcatSelect.options[i] = new Option(subsubcats[contract_id][i].subcontract,subsubcats[contract_id][i].subcontract_id);
}
}
</script>

Categories

Resources