Creating JavaScript object from MySQL DATABASE (ie multiple tables) - javascript

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.

Related

Search form using ajax, php and json

i'm currently learning javascript through my school and I'm completely stuck on trying to make a search form work.
The problem I have is that I can't get it to show all results from the sql query.
The code looks like this:
$(document).ready(function(){
var searchfield = document.getElementById("searchfield");
var searchresult = document.getElementById("searchresult");
$(searchfield).on("keyup", function(){
var q = this.value;
console.log(q +"'This value'");
var str = "";
var url = "searchscript.php?q="+q;
$.ajax({
url:url,
type:'post',
dataType: 'json',
success: function(resultat){
console.log("resultatet är:" + resultat.ProduktNamn);
for(var i = 0; i < resultat.ProduktNamn.length; i++) {
str += resultat.ProduktNamn + "<br>";
}
searchresult.innerHTML = str;
}
})
});
});
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
while ($row = $resultat->fetch_assoc()) {
echo json_encode($row);
}
}
?>
As soon as the result of the query has more than 1 property, no matter how I do it it won't show any results, only when I narrow down the search so that only one product is found it shows it.
I'm new to javascript, but I'm pretty sure this has to do with the fact that the way I'm doing it on the PHP side makes it so it returns every product as a single object, not within an array or anything, so when I get the data back on the javascript side I have trouble looping through it.
So basically, say I have these products
"Banana Chiquita"
"Banana Chichi"
"Banana"
I will only get a result on the javascript side once I've written atleast "Banana chiq" in the search field so the php side only returns 1 object.
Sorry for my terrible explaination :/
Well, first you should make a 2D array and then encode it to JSON. Currently, you are writing out each record as a JSON string which will work for a single record but not for multiple records. See the corrected PHP code.
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
$rows = array();
while ($row = $resultat->fetch_assoc()) {
array_push($rows,$row);
}
echo json_encode($rows);
}
?>

PHP - When a checkbox gets checked send a request to run a query on the database

So I've been working on this code for awhile now and I've done a lot of debugging but can't figure this out. What I want to do is: if a checkbox is checked send a request to run a query on the mySQL database FROM items WHERE .class(of the checkbox) '<' this.value(of the checkbox again) then get the filtered results and then use my javascript to format it:
index.php:
<form>
<label><input type="checkbox" class="calories "name="calories" value="300">Less than 300</label><br>
<label><input type="checkbox" class="calories" name="calories" value="500">Less than 500</label><br>
</form>
<script>
$("input.calories:checkbox").on("change",function(){
if(this.checked){
var column = $(this).attr('class'); //The class determines which column of the table is called
var value = $(this).attr('value'); //Takes the numeric value from the selected box
console.log(column);
//$.post('showItems.php', {type: column});
//$.post('showItems.php', {value: value});
//Can we call the php code above to run a query using variables column and value?
//make a php function above and call it
// function below will run showItemss.php?c=column?v=value
$.ajax({
type: "POST",
url: "showItems.php" ,
data: { c: column,
v: value},
error: function(){console.log("error")},
success: function(data) {
console.log("success");
console.log(test);
console.log(filteredList);
</script>
Here is the PHP file showItems.php I'm calling (the relevant part):
//This array holds items from database.
$itemList = array();
//Connect and Select
$con = makeConnection($dbhost, $dbuser, $dbpass, $dbname);
//Get the value and type from the javascript below
//If the type is null display the whole table
$c = $_POST['c'];
//echo $c;
//$v = mysqli_real_escape_string($con,$v);
//$type = $_POST['value'];
if($c==null){
$query = "SELECT * FROM items";
}
else{
$v = $_POST['v'];
$query = "SELECT * FROM items WHERE ".$c."< ".$v."";
}
$result = mysqli_query($con, $query);
//Collect data from all items
while($row = $result->fetch_assoc())
{
$tempItem = new Item($row['itemID'], $row['itemName'], $row['price'], $row['description'], $row['calories'], $row['protein'], $row['choles'], $row['sodi'], $row['picLink']);
$itemList[] = $tempItem;
}
echo json_encode($query);
?>
<script>
var test = <?php echo json_encode($query); ?>;
var filteredList = <?php echo json_encode($itemList); ?>;
</script>
So I want this code to be run every time I click a checkbox in my Index.php file so I can get the updated filtered items, $itemList, but I cannot figure out how to do this. Something I've done to test this is store my php values as javascript variables, Include showItems.php then console.log the variables from ShowItems.php in Index.php, and the query isn't being updated upon click which makes sense I guess. In the AJAX success function 'data' contains the entire HTML source with an updated query, but I can't figure out how use only the specific code I need in the success function. Any ideas at all would be helpful.
Try doing this:
Go from on("change",...) to on("click",...)
Also try using instead of this.checked, $(this).prop("checked") which will return you true or false depending on wether the checkbox is checked or not.
You might want to change either your selector or your checkbox classes because both are the same, and can give you undesired functionality in order to get your values when you click on a checkbox, since the selector finds you both checkboxes.
Hope this ideas can get you closer where you want to be.
Cheers

array_push flat array issue - need to be able to add multiple variables to the array

I am trying to add a pair of variables 'product_name' and 'photos' (which is the URL of the car photo) into an array. I have a friend that said my efforts are failing because I am pushing into a flat array. I've looked to see how to do this with variable pairs and am stymied. He had suggested pushing row into $isotopecubes instead of how I have it below, but when I try I am getting null values. I need to be able to access val.photo and val.product_name in my javascript call in my php file that references this ajax code.
Note: if I just use:
array_push($isotopecubes, $row['photo']);
I get back the following JSON response on my console:
"/images/photos/cars/vw/14_Virginia_L.jpg",
"/images/photos/cars/mazda/2013/14hybrid.jpg"
so I know I am reaching the database and getting the correct values. Here is my ajax code:
<?php
include '../../global_config.php';
include 'config.php';
if ($_GET['action'] == 'get-images') {
$selectSql = "SELECT product_name, photo FROM cars WHERE publish = 1;";
$isotopecubeResult = $db->query($selectSql);
$isotopecubes = array();
while($isotopecubeResult->fetchInto($row, DB_FETCHMODE_ASSOC)) {
array_push($isotopecubes, $row['photo'], $col['product_name']);
// $isotopecubes = array_merge($isotopecubes, $row['photo']);
}
echo json_encode($isotopecubes);
}
?>
It can be done by
<?php
include '../../global_config.php';
include 'config.php';
if ($_GET['action'] == 'get-images') {
$selectSql = "SELECT product_name, photo FROM cars WHERE publish = 1;";
$isotopecubeResult = $db->query($selectSql);
$isotopecubes = array();
while($isotopecubeResult->fetchInto($row, DB_FETCHMODE_ASSOC)) {
//array_push($isotopecubes, $row['photo'], $col['product_name']);
// $isotopecubes = array_merge($isotopecubes, $row['photo']);
$isotopecubes[] = array('product_name' => $row['product_name'], 'photo' => $row['photo']);
}
echo json_encode($isotopecubes);
}
?>
Now you will be able to get value through val.product_name and val.photo

Displaying query inside a div

Hi Guys I am stuck with my coding. I hope someone can help me with my problem
So I have this class (updateProgress.php) that pulls the value from the DB and process it thru ajax on the other page called data2.php and display the query when user press the show button to the in (updateProgress.php).
What i have in the data2.php is,
<?php
// IF SHOW KEY HAS BEEN PRESSED
if($_POST['action'] == 'show')
{
$sql = "SELECT * FROM SUB_MASTER_DRAWING
WHERE SUB_MASTER_DRAWING.HEAD_MARK = '{$_POST["hm"]}'";
$query = oci_parse($conn, $sql);
$query_exec = oci_execute($query);
echo "<table border='1'>";
while($row = oci_fetch_assoc($query)){
echo '<div id="content">';
echo '<table cellspacing = "0"';
echo '<tr><th>Head Mark</th>
<th>Cutting</th>
<th>Assembly</th>
<th>Welding</th>
<th>Drilling</th>
<th>Finishing</th>
</tr>';
echo "<tr><td><b>$row[HEAD_MARK]/$row[ID]</b></td>";
if ($row['CUTTING'] == 'Y'){
echo "<td><input type='checkbox' id='cuttingCheckbox' name='cuttingCheckbox' checked='checked' disabled='disabled'/></td>";
} else {
echo "<td><input type='checkbox' id='cuttingCheckbox' name='cuttingCheckbox' onClick='checkboxCheck()' /></td>";
}
?>
So my problem is when user check the checkbox, it should make a query to the database and update the corresponding value. I tried making the javascript function just to check if the checkbox action works on the outside the php tag but it just doesnt do anything.
is it because i pass all the table query to the so that it wont process the javascript ?
please help me
You already have checkbox with onClick='checkboxCheck()' assigned. Just make an ajax call from that javascript function and update whatever value you want from that call. You can create another php file to handle this ajax call.
function checkboxCheck() {
var checkbox1 = document.getElementById("cuttingCheckbox");
if (checkbox1.checked) {
alert('CHECKBOX CHECKED');
} else {
alert('CHECKBOX NOT CHECKED');
}
// Make Ajax call here, to call a php file
// which will update the db table
// You will have to pass other relevant variables like row id etc
}
That code is ready for a SQL Injection.
I'd suggest just using jQuery for handling the clicking of the checkbox:
$('#cuttingCheckbox').click(function() { /* function goes here */ });
(or use mousedown instead of click)
And then just have a simple AJAX call to a PHP file. AJAX is really simple and quick with jQuery.

Inserting MySQL results from PHP into JavaScript Array

I'm trying to make a very simple autocomplete function on a private website using a trie in JavaScript. Problem is the examples I have seen and trying are just using a predefined list in a JavaScript array.
e.g. var arrayObjects = ["Dog","Cat","House","Mouse"];
What I want to do is retrieve MySQL results using PHP and put them into a JavaScript array.
This is what I have so far for the PHP (the JavaScript is fine just need to populate the array):
<?php
$mysqli = new mysqli('SERVER', 'U/NAME', 'P/WORD', 'DB');
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
while($stmt->fetch())
{
printf("%s, ", $name);
}
?>
Then I want to insert essentially each value using something like mysql_fetch_array ($name); (I know this is incorrect but just to show you guys what's going on in my head)
<script> -- this is the javascript part
(function() {
<?php while $stmt=mysql_fetch_array($name))
{
?>
var arrayObjects = [<?php stmt($name) ?>];
<?php }
?>
I can retrieve the results echoing out fine, I can manipulate the trie fine without MYSQL results, I just can't put them together.
In this case, what you're doing is looping through your result array, and each time you're printing out the line var arrayObjects = [<?php stmt($name) ?>];. However this doesn't convert between the PHP array you're getting as a result, and a javascript array.
Since you started doing it this way, you can do:
<?php
//bind to $name
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
//put all of the resulting names into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);
?>
<script>
//now put it into the javascript
var arrayObjects = <?php echo $json_array; ?>
</script>
Use json_encode to turn your PHP array into a valid javascript object. For example, if you've got the results from your database in a php array called $array:
var obj = "<?php echo json_encode($array); ?>";
You can now use obj in your javascript code
For the auto-completion you can use the <datalist> tag. This is a relatively new feature in HTML5 (see support table) but the polyfill exists.
Fill the <option> tags in php when building the page and you a are done.

Categories