I have a .php file where I have some script running to display "cards". I have 6 cards showing and the text being displayed is hard coded. I am ready to start pulling from my database and remove my hard code sections.
//Set number of cards to show
multiplyNode(document.querySelector('.card_content'), 6, true);
var authors = ["Margaret", "Lucy", "Odessa", "Shifty", "Saggy", "Lady"];
var BookNumbers = [2563, 8547, 5896, 4157, 5823, 7963];
$(function(){box_title
//$(".card_content").clone(true).appendTo(".main_card_shell");
$('.box_title').each(function (i) {
$(this).html("<div class='card_name'>" + authors[i] + "</div>" +
"<div class='card_number'>" + BookNumbers[i] + "</div>" +
"<div class='tag_row'>" +
"<div class='sample_tag sample_tag4'></div>" +
"<div class='sample_tag sample_tag3'></div>" +
"</div>");
});
})
I know I can pull the data I want from my database via:
$result = $conn->query("SELECT `Author`, `Book_Num` FROM `Authors`");
but how is the best way to get my $result to replace my hard coded authors and BookNumbers array?
You can loop through the results to build a php array with the same structure as your javascript arrays, then use json_encode to convert it to a javascript array format.
<script type='text/javascript'>
<?php
$result = $conn->query("SELECT `Author`, `Book_Num` FROM `Authors`");
// loop through the results to build the php arrays
while($row = $result->fetch_array())
{
// set the author and book number to array with numeric key
$authors[] = $row['Author'];
$BookNumbers[] = $row['Book_Num'];
}
// use json_encode to convert the php array to an javascript array
echo "var authors = ".json_encode($authors).";\n";
echo "var BookNumbers = ".json_encode($BookNumbers).";\n";
?>
</script>
A comment: unless you need interactivity you could build the html with php without using jquery
Related
I'm a 'newbie' on stackoverflow but it is a source that I keep coming to regularly for tips.
I've picked up some code from the simple.html file accompanying the jsPDF auto-table plug-in but as it doesn't appear to pick up data from a php generated table.
I am trying to get the data into a format that can be transformed into a nice pdf report - 'with all the trimmings' - ie; page-breaks, headers on each page, alternate row-colours etc.
I've tried to get the data into a form that can be used by the jsPDF autotable but I'm going wrong in that it is just going through the array and keeping the last record and printing that in pdf format. Code shown below.
<button onclick="generate()">Generate pdf</button>
<script src="/js//jspdf.debug.js"></script>
<script src="/js/jspdf.plugin.autotable.js"></script>
<?php
$link = mysqli_connect('localhost','user','password','database');
if(!$link)
{
echo 'Database Error: ' . mysqli_connect_error() ;
exit;
}
$results=array();
$sql_staff = "SELECT staff_id, staff_firstname, staff_lastname, staff_username, staff_chargerate, staff_lastlogin FROM tblstaff ORDER BY staff_lastname ASC, staff_firstname ASC ";
$result_staff = mysqli_query($link,$sql_staff);
while($row = mysqli_fetch_array($result_staff)){
$results[0] = $row['staff_id'];
$results[1] = $row['staff_firstname'] . " " . $row['staff_lastname'];
$results[2] = $row['staff_username'];
$results[3] = $row['staff_chargerate'];
$results[4] = $row['staff_lastlogin'];
echo json_encode($results);
$data = json_encode($results);
}
?>
<script>
function generate() {
var head = [["ID", "Staff Name", "Username", "Charge-rate", "Last Log-in"]];
var body = [
<?echo $data;?>
];
var doc = new jsPDF();
doc.autoTable({head: head, body: body});
doc.output("dataurlnewwindow");
}
</script>
I think that the problem lays around the line $data = json_encode($results); but I don't know enough about either PHP or Javascript to determine how the code needs to be altered to produce a full PDF report. Can anyone assist please?
Your issue is probably related to overwriting the values in the $results array which means you will get one item instead of an array of items. You probably want something like this:
$results = array();
while($row = mysqli_fetch_array($result_staff)){
$dataRow = array();
array_push($dataRow, $row['staff_id']);
array_push($dataRow, $row['staff_firstname'] . " " . $row['staff_lastname']);
// etc
array_push($results, $dataRow);
}
$data = json_encode($results);
I am trying to insert html code through a php variable in javascript. I am getting the following error below. Please can someone advise?
Error Message: "Unexpected Identifier 'Inactive'" ($option has values 'Inactive'/ 'Active')
PHP
$tr_active_Options = '';
$sql1 = "SELECT status FROM tr_active";
$result = $mysqli -> query($sql1);
while($row = $result -> fetch_assoc()){
$option = $row['status'];
$option = '<div class="dpOtions" onclick="track.addChosenOption(\''.$option.'\', \'act_ui\')">'.$option.'</div>';
$tr_active_Options .= $option;
}
$tr_active = '<div class="drpClass"><div class="dropOptionsDiv" id="actList_ui">'.$tr_active_Options.'</div></div>';
JAVASCRIPT
document.getElementById('anchor').innerHTML = '<div id="editWrap"><?php echo $tr_active; ?></div>';
The ' in your string are terminating the JavaScript string you've started with '.
You can safely have PHP generate a string for use in JavaScript using json_encode, like so:
document.getElementById('anchor').innerHTML =
'<div id="editWrap">' +
<?php echo json_encode($tr_active); ?> +
'</div>';
Note how the JavaScript string ends, then we use + to join it with the one that PHP will output (json_encode will handle the strings), then we + it with another JavaScript string after it. What the browser will see will look like this:
document.getElementById('anchor').innerHTML =
'<div id="editWrap">' +
"contents of $tr_active here" +
'</div>';
...which is valid.
That said: Using PHP to generate HTML with embedded JavaScript inside attributes is asking for a world of hurt. Separate those concerns! :-)
Scenario: I need to compare a database cell on the page load (php) against itself in an interval loop every x amount of minutes for changes.
My Initial load data looks like this:
var olddata = JSON.stringify(<?php echo json_encode($data1); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data2); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data3); ?>);
So on page load, I save the cells into a javascript variable with a "~|~" delimiter, where $data1, $data2, and $data3 are 3 different cells in the database (arrays of data).
And my interval loop data (ajax call) looks like this:
// PHP on the AJAX page
echo json_encode($data1)."~|~".json_encode($data2). "~|~".json_encode($data3);
// AJAX code that gets called every x Intervals
$.get("ajaxpage.php", function(data) {
if (data == olddata) {
console.log("Good!");
}
});
When I compare olddata against data they look almost identical except... data that has a / in it will look like \/ in the data variable and not in theolddata` variable.
Example:
"10":["10"],"11":["11 5\/25"] // data = return from the AJAX call
"10":["10"],"11":["11 5/25"] // olddata = what was originally echoed on page load.
How can I compare the two so that they will match perfectly? So that what I echo from the database and json_encode, will line up with what I get from the exact same thing echoed on a page and jason encoded from the json function return.
Note: If I remove the JSON.stringify then it will return [object Object]
You're using a very bad practice. Just use AJAX to get this:
var olddata = JSON.stringify(<?php echo json_encode($data1); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data2); ?>) + "~|~" +
JSON.stringify(<?php echo json_encode($data3); ?>);
And store "olddata" in a JavaScript Global var, then compare the old data with the new data returned by $.get. This isn't the solution for your bug, but it's a better way to do what you're doing.
To fix the bug just declare the type of the return value in the your $.get function, like that:
$.get("ajaxpage.php", function(data) {
if (data == olddata) {
console.log("Good!");
}
}, 'text');
For more information about the return type, look the jQuery Documentation: jQuery $.get Documentation
Just change it to:
var olddata = '<?php echo json_encode($data1, JSON_HEX_APOS); ?>~|~<?php echo json_encode($data2, JSON_HEX_APOS); ?>~|~<?php echo json_encode($data3, JSON_HEX_APOS); ?>';
And the backend to:
echo json_encode($data1, JSON_HEX_APOS)."~|~".json_encode($data2, JSON_HEX_APOS). "~|~".json_encode($data3, JSON_HEX_APOS);
Now you're simply comparing two strings.
I am working with two different tables that are in different servers.
I am trying to compare the USERNAME field values from table "workstation_userlogged" and
the MEMO_CODE field value (they are usernames) from table "telephony". I get the "memo_code" values with the use of a Stored Procedure as you will see in the code below.
How can I save all the results returned from both tables, loop through them to match all usernames and then save the data so it can be returned with AJAX? This script will only run when an AJAX request button is clicked. So, I need to bring the data back and display it like so:
If matching usernames from both tables:
user: JOE time: 300
If no matching usernames:
user: MARC time: N/A
Some usernames from "workstation_userlogged" do not exist in the other table and vice versa.
I know it has to do with handling arrays and all but I've been stuck for hours and wasn't able to accomplish it.I need to clarify things please ask.
Thanks in advance!
map.php HTML/AJAX: How do I fix this?
<!-- Show the results here-->
<div id="resultdiv" class="resultdiv" style="display:none"> </div>
<div id="aht"><!--aht button-->
<button id="aht_button">AHT</button>
</div><!--aht button-->
<script type="text/javascript">
$(document).ready(function() {
$('#aht').click(function(){
$.ajax({
type:"POST",
url : "show_aht.php",
data: { }, // pass data here
success : function(data){
}//end success
});//end ajax
});//end click
});//end rdy
show_aht.php: when AJAX request is sent
<?php
Stored PRocedure just to show what I did:
//get the StoredProcedure from the "query" field in the overlay table
//and store it as a variable for later use for the AHT button
if($row = mysqli_fetch_assoc($query_overlay_result)){
$sp_value = $row['query'];
}
Table workstation_userlogged:
The results from this WHILE LOOP need to be matched with the results of the StoredProcedure below
//the displayed users values will have to be matched with memo_code
$user_data = array();
while($row = mysqli_fetch_assoc($get_user_result)){
$user_data[] = "user: " .$row['username'];
}
This is where I am trying to compare both usernames and bring the data back
to map.php but had no luck.
/****************************************************
Execute the sp_value query when AHT button is clicked
/****************************************************/
//loop the result set
$memo_data = array();
while ($row = mysqli_fetch_assoc($dbh2_result)){
$memo_data[] = $row['memo_code'] . " " . $row['avg_handle_time'];
}
/*THIS ISNT WORKING*/
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m['username'])
echo " user: " .$m['username']. " time: " . $v['avg_handle_time'] . "<br>";
}
}
?>
So the first mistake is your use of json_encode($user_data) json encode is a function which converts an array into a string in the format of javascript object notation. It's to be used in conjecture with something like echo json_encode($obj); and recieved in javascript obj = JSON.parse(json);
Now since you have 2 arrays what you need to do is loop through both to find the matching names:
I'm not sure what memo_code is but it needs to be a username.
Your query is incorrect change it to something like.
$result = $sql->query("SELECT username FROM `$table1`;");
for ($user_data= array (); $row = $result->fetch_assoc(); $set[] = $row);
$result2 = $sql->query("SELECT memo_code FROM `$table2`;");
for ($memo_data= array (); $row = $result2->fetch_assoc(); $set[] = $row);
Now you can finally use the loop correctly:
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m['username '])
echo " user: " .$m['username ']. " time: " . $v['avg_handle_time'] . "<br>";
}
}
I found the solution basically I wasnt`t comparing arrays properly so here below is the new comparison.
$user_data = array();
while($row = mysqli_fetch_assoc($get_user_result)){
$user_data[] = $row['username'];
}
/****************************************************/
//loop the result set
$memo_data = array();
while ($row = mysqli_fetch_assoc($dbh2_result)){
$memo_data[] = array("memo_code" => $row['memo_code'],
"avg_handle_time" => $row['avg_handle_time']);
}
/**comparing usernames from both arrays*/
foreach($memo_data as $v){
foreach($user_data as $m){
//echo 'mem code is:'.$v['memo_code'].'username is:'.$m['username'];
if($v['memo_code'] == $m){
echo " User: " .$m. " Time: " . $v['avg_handle_time'] . "<br>";
}
elseif( $v['memo_code'] != $m){
echo " User: " . $m . " Time: N/A <br>";
}
}
}
Sorry to add another JavaScript object to the mix. I'm just having a little trouble wrapping my head around this as it is a little more complex than i have ever dealt with.
Like the title states, i'm trying to create a JavaScript Object or perhaps a multidimensional array of a MySQL Database. For testing purposes i'm only using three tables from my database even though eventually it will store tens of tables. These tables are called "Interfaces", "IPAM", and "DNSF".
The reason i would like to complete this task is that, i am trying to create a heavy ajax page which dynamically knows when tables are added, updated, deleted etc, and automatically reflects this without having to add more code. I am doing this by writing javascript with php in addition to various other ajax callbacks spitting out html and variables.
Let me start out with my hardcoded HTML. All other html is created dynamically. This too will soon be created dynamically to add buttons to my website without adding code.
<body>
<div class = "form">
<button type="button" class = "formbutton" value = "Interfaces" onclick="inputChoice('Interfaces')">Interfaces</button>
<button type="button" class = "formbutton" value = "IPAM" onclick="inputChoice('IPAM')">IPAM</button>
<button type="button" class = "formbutton" value = "DNSR" onclick="inputChoice('DNSR')">DNSR</button>
</div>
<div class = "tableDiv" id="myTableDiv" style="height:1000px;width:1000px;border:1px solid #ccc; overflow: scroll;"><table id = "myTable"></table></div>
</body>
Before any buttons or events are executed, the first thign my page does is issue ajax requests within a $( document ).ready(function() { function. My issue is that i have to code a seperate ajax request for every single table. I'll show an example here where i fetch interface table data:
$.ajax({
url:"/ryan/nonEmber/ajax.php?table=Interfaces",
beforeSend: function(XMLHttpRequest){},
success: function(data, textStatus) {
InterfacesCols = data.split(" ");
InterfacesCols.pop();
$.getJSON("/ryan/nonEmber/getJson.php?table=Interfaces", function( data ){
var items = [];
$.each(data.post, function(key, val){
items.push(val);
});
for(i = 0; i < items.length; i++){
var myString = '<tr id = "visibleRow">';
for(j = 0; j < InterfacesCols.length; j++){
if(InterfacesCols[j] != null){
myString = myString + '<td id = "visibleDef">' + items[i][InterfacesCols[j]] +'</td>';
}
}
myString = myString + '</tr>';
Interfaces.push(myString);
}
});
}
});
This ajax request ultimately creates an array of html strings that are used to create the table. Interfaces[] contains each html row. InterfacesCols contains the names of each column. I have to write this block of code for every single table.
What i want to do is put my "Interfaces[]" like arrays and "InterfacesCols[]" like arrays within a master array so that i can create a template and not have tons of the same code.
Lets call this master array tables. This would allow me to put my ajax in a for loop and loop through every table array rather than hardcode it.
tables[0] would be interfaces[], tables[1] would be ipam etc.
In addition to my ajax request blocks where i initially gather my data from the database. I also have my function "inputChoice(string)", where i actually generate a table from this data. I do so by changing inner html of my table. I dont wan't to have to redirect my page. This works fine, but once again i have to create a new block of code for every single table. These blocks of code are massive right now because they include garbage collection for the DOM and also the code for handling massive data sets(>10,000) without browser slow down. I will refrain from posting that block unless necessary. The ajax calls require the same thing.
Here is the php where i originally create the empty array variables by generating javascript:
<?php
$sql= "SELECT
TABLE_NAME
FROM information_schema.TABLES
WHERE
TABLE_TYPE='BASE TABLE'
AND TABLE_SCHEMA='NJVCtestDB'";
$stmt = $DBH->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
echo '<script>';
try{
$stmt->execute();
echo 'var tables = [];';
while($row = $stmt->fetch()){
echo 'var '.$row['TABLE_NAME'].' =[];';
echo 'tables += '.$row['TABLE_NAME'].';';
echo 'var '.$row['TABLE_NAME'].'Cols =[];';
}
echo 'console.log(tables[1]);';
}catch(PDOException $e){
echo $e;
}
echo '</script>';
?>
The above php is only called by using an statement on my index. No Ajax.
The link my ajax calls is this:
<?
$sql = "DESCRIBE ".$_GET['table'];
$stmt = $DBH->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$colnames;
try{
$stmt->execute();
//$stmt2->execute();
$colnames = $stmt->fetchAll(PDO::FETCH_COLUMN);
}
catch(PDOException $e){
echo $e;
}
foreach($colnames as $value){
print $value ." ";
}
?>
The above ajax servers only the purpose of fetching column names and returning the names in a space delimeted string to be parsed and turned into an array via javascript, which you can see in my ajax call.
My getJson ajax code is here:
<?php
include "connect.php";
$sql = "DESCRIBE ".$_GET['table'];
$stmt = $DBH->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$colnames;
try{
$stmt->execute();
$colnames = $stmt->fetchAll(PDO::FETCH_COLUMN);
}
catch(PDOException $e){
echo $e;
}
$sql = "SELECT * FROM ".$_GET['table']." LIMIT 17000";
$stmt2 = $DBH->prepare($sql);
$stmt2->setFetchMode(PDO::FETCH_ASSOC);
try{
$stmt2->execute();
while($row = $stmt2->fetch()){
foreach($colnames as $value){
if($row[$value] == null){
$row[$value] = "";
}
}
$row = array('id' => $i) + $row;
$items['post'][]=($row);
$i++;
}
}
catch(PDOExcetipn $e){
echo $e;
}
print json_encode($items);
?>
The above php seems slightly redundant to me as i fetch the column names again. However this time i also include the actual data. Line by line.
This is basically all of my code i have written for this project. The only code i did not include was my javascript inputChoice() function. Which as i stated above is very bulky and really doesnt do anything the ajax doesnt do when it comes to utilizing the arrays. This is a massive post, so i apologize for the wall of text. I am not sure exactly what the next step is for me to code this better in the way i described. Any input would be very much appreciated!
If I'm correct you want to automate the table generating.
Your index php block retrieves all tables from the DB.
$sql= "SELECT
TABLE_NAME
FROM information_schema.TABLES
WHERE
TABLE_TYPE='BASE TABLE'
AND TABLE_SCHEMA='NJVCtestDB'";
So we need to add those to a master table pseudo code:
tables = [];
for (table in tableSQL)
{
tables[table] = tableSQL[table];
tables[table]['cols'] = [];
}
Now you have a master table array containing all your tables.
Let's loop through these. pseudo code:
for (table in tables)
{
retrieveColsWithData(table);
}
function retrieveColsWithData(tableKey)
{
//table = key = table name in DB
$.ajax({url:"/ryan/nonEmber/ajax.php?table="+table, etc.
//rest of the ajax call you're doing. Pass the key var to the JSON function
});
}
The function above loops through all the tables and retrieves the colls. When the JSON request returns you simply add the colls to table[key]['cols'].
Now you can simply iterate over the tables master with a for in or Object.keys and draw the HTML containing the data.
You can reuse retrieveColsWithData connected to your inputChoice to reload the data.