JSON Array values to use in JQuery and execute function - javascript

I’m reading X,Y Coordinates from MySQL Database.
2 files, pretend the connection is there : coordinate_array, and map.php
Update here In coordinate_array: I am making a multidimensional arrays so I can then use json_encode($desk). I only need x,y values for the Javascript part.
<?php
include 'db_conn.php';
header('Content-Type: application/json');
$select_coordinate_query = "SELECT x_coord, y_coord FROM coordinates";
$result = mysqli_query($conn,$select_coordinate_query);
//see if query is good
if($result === false) {
die(mysqli_error());
}
//array that will have number of desks in map area
$desk = array(); // just added
while($row = mysqli_fetch_assoc($result)){
//get desk array count
$desk[] = array( array("x" => $row['x_coord']),
array("y" => $row['y_coord'])
);
} //end while loop
echo json_encode($desk); //encode array
?>
The code above gives me this :
[[{"x":"20"},{"y":"20"}],[{"x":"30"},{"y":"30"}],[{"x":"40"},{"y":"40"}],[{"x":"50"},{"y":"50"}]]
In map.php : I am trying to get those value with the use of JQuery. I want to get the values and run a loop that will execute my Paint function which will keep drawing rectangles for every row thats in the table. I am very new with JSON and JQuery and starting to use it.
<canvas id="imageView" width="600" height="500"></canvas>
<script type="text/javascript">
NEED HELP HERE PLEASE
//I have no idea how to get the encoded values
$(document).ready(function(){
$.getJSON('coordinate_array.php', function(data)){
$.each(data, function(k,v){
Paint(v[0].x, v[1].y);
});//end each
});//end get json
});//end rdy func
I WANT TO EXECUTE THIS FUNCTION
//function to paint rectangles
function Paint(x,y)
{
var ctx, cv;
cv = document.getElementById('imageView');
ctx = cv.getContext('2d');
ctx.lineWidth = 5;
ctx.strokeStyle = '#000000';
//x-axis,y-axis,x-width,y-width
ctx.strokeRect(x, y, x+100 , y+100);
}
</script>
Thank you in advance it’s much appreciated!

You're doing the json wrong. it should be encoded AFTER your DB fetch loop completes. Since you're doing the encoding inside the loop, you're spitting out multiple independent JSON-encoded strings, which will be treated as a syntax error on the receiving end.
e.g.
while($something) {
echo json_encode($some_array);
}
will spit out
[something][something][something]
three separate json-encoded arrays jammed up against each other. What you want is something more like this:
while($something) {
build_array();
}
echo json_encode($array);
which would spit out
[something,something,soemthing]
instead.

Try to use
header('Content-Type: application/json');
in coordinate_array.php

Related

Trying to get php tables into pdf format – using jsPDF-auto-table to get the result of php query(multiple records)into a nicely formatted pdf file

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);

Array from PHP to Javascript (Using JQuery)

I have some problems trying to redraw some markers (on google maps) from a database, use the form jquery
Index.html:
var map;
var datos;
function updateLocations(){
var post= $.post('php/getLoc.php',{table: "Auto"), function f(data){
datos =[]; //clear array with the last positions
datos = data;
drawAutos(datos); }); }
php/getLoc.php:
$link = mysql_connect("localhost","root","") or die('could not connect: '.mysql_error());
mysql_select_db("database") or die ('could not select db');
$autos= "SELECT * FROM autos ORDER BY auto_id ASC";
$result=mysql_query($autos) or die('query fail'.mysql_error());
$datos= array();
while($row= mysql_fetch_assoc($result)){
$datos[] = array(
0=>$row['taxi_id'],
1=>$row['lat'],
2=>$row['lng'],
3=>$row['availability']);}
$out = array_values($datos);
var_dump(json_encode($out));
mysql_free_result($result);
mysql_close($link);
The query is correct, but I get the information otherwise. there is a way to remove the string () "" (see picture), I have tried using $.parseJSON(data) and $.getJSON(data) but not work for me =(
echo json_encode($out); instead of var_dump($out);. Also, mysql is depreciated. Use mysqli or PDO or something else. The Object Oriented Approach will save you time. Also, you can $mysqli_result->fetch_all(MYSQLI_ASSOC) instead of making your while loop.
Ok, is working now :), thanks to PHPglue, I use
PHP File:
echo json_encode($out)
I also do in Index File:
var obj = $.parseJSON(data);
drawAutos(obj);

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

MySql and PHP loop to draw squares with x,y coordinates

I updated my code. It has Javascript,PHP,JSON and JQuery. I’m reading X,Y Coordinates from
MySQL Database.
I am now using 3 files : coordinate_array, db_conn and map.php
Connection :
<?php
//declaring connection
$db_user = "u";
$db_pwd = "p";
$db_server = "v";
$db_name = "sandbox";
//1. connection to the database
$conn = mysqli_connect($db_server, $db_user, $db_pwd);
//check connection
if(!$conn){
die("Database connection failed: " . mysqli_error());
}else{
echo "connected to MySQL<br>";
}
// 2. Select a database to use
$db_select = mysqli_select_db($conn, $db_name);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
mysqli_close($conn);
?>
In coordinate_array: I am making a multidimensional arrays so I can draw all of the rectangles being
fetch by my query, I then use json_encode($desk). I am ignoring the coordinate_id from the table
since I only need x,y values for the Javascript part.
<?php
$select_coordinate_query = "SELECT * FROM coordinates";// WHERE coordinate_id ='1'
$result = mysqli_query($conn,$select_coordinate_query);
//see if query is good
if($result === false) {
die(mysqli_error());
}
//array that will have number of desks in map area
while($row = mysqli_fetch_assoc($result)){
//get desk array count
$desk = array( array("x" => $row['x_coord']),
array("y" =>
$row['y_coord'])
);
// Frame JSON
// Return the x, y JSON here
echo json_encode($desk);
} //end while loop
?>
In map.php : I am trying to get those value with the use of JQuery. I want to get the values and run a
loop that will execute my Paint function which will keep drawing rectangles for every row thats in the
table. I am very new with JSON and JQuery and starting to use it.
<div class="section_a" >
<p>Section A</p>
<canvas id="imageView" width="600"
height="500"></canvas>
<script type="text/javascript">
$(document).ready(function(){
/* call the php that has the php array which is json_encoded */
$.getJSON('coordinate_array.php', function(data) {
/* data will hold the php array as a javascript object */
if(data != null){
$.parseJSON(data);
$(data).each(Paint(x,y)){
//get values from json
//for every row run the functionpaint by passing X,Y coordinate
});//end getJson
}//end if
}); //end rdy func
});//end func
//function to paint rectangles
function Paint(x,y)
{
var ctx, cv;
cv = document.getElementById('imageView');
ctx = cv.getContext('2d');
ctx.lineWidth = 5;
ctx.strokeStyle = '#000000';
//x-axis,y-axis,x-width,y-width
ctx.strokeRect(x, y, x+100 , y+100);
}
</script>
</div> <!-- end div section_a -->
Also, do I have the correct syntax for my when including my jquery file.. its in the same as
every other file that I’m using.
Another question I have is: Is it good to include the connection file in every file and close it at the end
or keep the connection open in my file where I havethe connection established?
Thank you in advance it’s much appreciated!
I would like to suggest a better way to keep the code simple and clean.
Create a web service interface to return the x,y data in an array.
This interface can read from the database and shall return x,y co-ordinates in JSON.
Use Jquery Ajax call to get these details and paint the screen.
Better use RxJS for easier painting.
Here is the sample code for web interface:
<?php
// I assume you have not created connection object -- I don't see one in your code
$conn=mysqli_connect("localhost","my_user","my_password","my_db"); // replace the credentials and db name
// Check connection
$select_coordinate_query = "SELECT * FROM coordinates";
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($conn,$select_coordinate_query);
//see if query is good -- ## Better check for row count
if($result === false)
{
die(mysqli_error());
}
//array that will have number of desks in map area
while($row == mysqli_fetch_assoc($result)){ // double equal to missing...you will never receive the data
//get desk array count
//THIS IS WHERE I NEED HELP**
$desk = array( array("x" => $row['x_coord']),array("y" => $row['y_coord']) );
//x, y coordinates
$x_pos = $desk['x'];
$y_pos = $desk['y'];
//x,y width and height
$x_size = $x_pos + 40;
$y_size = $y_pos + 10;
// Frame JSON
// Return the x, y JSON here
} //end while loop ?>
Here is the client code:
<div class="section_a" >
<p>Section A</p>
<canvas id="imageView" width="600" height="500"></canvas>
<script type="text/javascript">
function callWS()
{
// Make XHR call here and read JSON values
// Loop through and paint by calling f(Paint)
}
function Paint(x,y)
{
var ctx, cv;
cv = document.getElementById('imageView');
ctx = cv.getContext('2d');
ctx.lineWidth = 5;
ctx.strokeStyle = '#000000';
ctx.strokeRect(x, y,100 , 100);
}
</script>
</div>
You can call these functions in any event you would want. Code is untested. Note that you were creating Canvas many times earlier but here it's created once and you can draw squares on the canvas.

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