I have seen some answers similar to this but they wont work for me.
I want to select data from a mysql database using mysqli / PHP and then pass the results to javascript.
I have the $conn stuff just above this, my code is at the very top of the file above the html, my script tags are in the body of the html. Is the correct place to have them? This just returns undefined, and if i try tweaking it i get unexpected < in index where i try and save it to the var ar. Or i can get unexpected ';' at the same line. Code shown below return unexpected ';'.
PHP
$query = "SELECT * FROM table";
$result = $conn->query($query);
while($row = $result->fetch_array())
{
$rows[] = $row;
}
$conn->close();
JavaScript
<script type="text/javascript">
var ar = <?php echo json_encode($rows)?>;
console.log(ar[0][0]);
</script>
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'm building a leaflet web app which stores messages assigned to geolocations.
I add data one line at a time by sending it from javascript to PHP using:
$name = mysqli_real_escape_string($conn, $_POST['NAME']);
$latitude = mysqli_real_escape_string($conn, $_POST['LATITUDE']);
$longitude = mysqli_real_escape_string($conn, $_POST['LONGITUDE']);
$message = mysqli_real_escape_string($conn, $_POST['MESSAGE']);
$sql = "INSERT INTO geoData (NAME,LATITUDE,LONGITUDE,MESSAGE)
VALUES ('$name', '$latitude', '$longitude', '$message')";
I get the data back out using PHP to echo the data back to javascript using:
$conn = mysqli_connect($dbServername,$dbUsername, $dbPassword, $dbName);
if(! $conn ){
die('Could not connect: ' . mysqli_error());
}
$sql = 'SELECT * FROM geoData';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
} else {
echo "0 results";
}
mysqli_close($conn);
<script type="text/javascript">
var data = JSON.parse( '<?php echo json_encode($rows); ?> ' );
</script>
This works fine UNLESS the message has special characters such as apostrophes for example 'Dave's dogs's bone'. This creates an error
What is the best practise for such an application which uses PHP and javascript. I think I need some way to encode the special characters which javascript can then decode and display.
The error comes as:
Uncaught SyntaxError: missing ) after argument list
<script type="text/javascript">
var data = JSON.parse( '[{"NAME":"The Kennel","LATITUDE":"50.7599143982","LONGITUDE":"-1.3100980520","MESSAGE","Dave's Dog's Bone"}] ' );
</script>
Many thanks
The issue is your JSON.parse() which isn't needed at all in this case.
Change:
var data = JSON.parse( '<?php echo json_encode($rows); ?> ' );
to
var data = <?= json_encode($rows); ?>;
JSON.parse() is for parsing stringified json. Echoing the result from json_encode() will give you the correct result straight away.
Side note
I would recommend adding $rows = []; before your if (mysqli_num_rows($result) > 0) or json_encode($rows) will throw an "undefined variable" if the query doesn't return any results (since that variable currently is created inside the loop when you're looping through the results).
Side note 2
When making database queries, it's recommended to use parameterized Prepared Statements instead of using mysqli_real_escape_string() for manually escaping and building your queries. Prepared statements are currently the recommended way to protect yourself against SQL injections and makes sure you don't forget or miss to escape some value.
You produce that error yourself by adding ' in json. If you want check that use this:
JSON.parse( '[{"NAME":"The Kennel","LATITUDE":"50.7599143982","LONGDITUTE":"-1.3100980520","type":"bad","reason":"Dave\'s Dog\'s Bone","improvement":"","reviewed":"0"}] ' );
And if you want correct that in main code use str.replace(/'/g, '"') for your var data, before parse it to json.
I am trying to call JavaScript function in php and pass it value of a php json array type variable as an argument. I found from search on SO forum one way to do this is to echo/print_r the variable value to a js var inside a js script within php code. I am trying do it this way but I am not able to recover from 'unexpected token: identifier error ' while doing so.
I am trying to figure out the reason of syntax error but couldn't. I tried different ways what I found; by putting quotes single/double around php part within the script, without quotes as some places I found solution with quotes some places without but no one seems working.
Here is my code. It will be very helpful if someone sees it and point what is causing this error.
<script>
dspChrt(WData);
.......
</script>
<HTML>
<?php
$WData;
require("Connection.php");
try {
$stmt = $conn->prepare("Select humidity, temperature FROM weatherdata");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach($stmt->fetchAll() as $k=>$v) {
$WData = json_encode($v);
//print_r($WData);
}?>
<script>
var Wdata = <?php print_r($WData);?>
dspChrt(WData);
consol.log(WData);
</script>
<?php
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
</HTML>
First of all you need to parse the JSON using JSON.parse.
Also you need to change the sequence of php and javascript code.
If you want to assign php data to Javascript variable, please retrieve data using php first and write javascript code below it.
For example :
<?php
$v = array(1,2,3);
$data = json_encode($v);
?>
<script>
var WData = JSON.parse('<?php echo $data; ?>');
dspChrt(WData);
</script>
You should encode your PHP into JSON to pass it to JavaScript.
And you should prepare your data first.
<?php
$data = array('xxx'=>'yyy');
?>
<script>
var data = <?php echo json_encode($data); ?>;
//then in js, use the data
</script>
for your code, there are too many errors to be fixed:
<HTML>
<?php
require("Connection.php");
$stmt = $conn->prepare("Select humidity, temperature FROM weatherdata");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$WData = array();
foreach($stmt->fetchAll() as $k=>$v) {
$WData[] = $v;
}
?>
<script>
var WData = <?php echo json_encode($WData);?>;
console.log(WData);
dspChrt(WData);
</script>
</HTML>
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);
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.