Inserting MySQL results from PHP into JavaScript Array - javascript

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.

Related

'unexpected token: identifier error' - assigning php json array type variable value to a javascript function from php code

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>

mysqli select query to JS 2d array

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>

Autocomplete not working when array is filled from database

I used to use this kind of code before like 1 year ago and it worked.
Now I got a problem with the php code when I fill my array with elements from the database I can't do the autocomplete, but when I comment the part where I get the code form the database and uncomment //$elements = array("25qt", "45tr", "az12"); than the autocomplete works.
It looks like the array is filled correctly from the database cause when I open the php file alone and do a var_dump($elements); i get the content of the array accordingly. Any idea why its not working when i fill the array from the db but it works if I use an array like $elements = array("25qt", "45tr", "az12");.
HTML code:
<input id="tegjithepjeset" type="text" class="form-control">
jQuery code:
<script type="text/javascript">
$(document).ready(function(){
$("#tegjithepjeset").autocomplete({
source:'allParts.php',
minLength:1
});
});
</script>
Php code:
<?php
// An empty array:
$data = array();
// Create connection
include 'dbinfo.php';
$con=#mysqli_connect("$host","$user","$password","$db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$queryString = "SELECT code FROM ".$table;
$query =mysqli_query($con,$queryString);
$elements = array();
while($rowDB=mysqli_fetch_array($query)){
$elements[]="".$rowDB[0];
}
//var_dump($elements);
//$elements = array("25qt", "45tr", "az12");
//Loop through the array to find matches:
foreach ($elements as $elm) {
// Add matches to the $data array:
if (stripos($elm, $_GET['term']) !== false) $data[] = $elm;//here we fill our empty array with values
} // End of FOREACH.
// Return the data:
echo json_encode($data);
?>
Replace the $elements array code as shown below.
$elements = array();
while($rowDB=mysqli_fetch_array($query)){
// $elements[]="".$rowDB[0];
$elements[]=$rowDB[0];
}

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

convert JS var to PHP and vice versa

Here I am getting values from textarea in array variable.
After that I convert javascript variable to PHP variable and perform some processing over it.
After process completed again I convert PHP to JS and alert. But when I alert, it gives empty result.
<script>
$( "#convert" ).click(function() {
var arabic = document.getElementById("ar").value; // ar is id of text area
<?php $ar_terms = "<script>document.write(arabic)</script>"?>
<?php
$string=implode(",",$ar_terms);
$result = array();
foreach ($ar_terms as $term) {
// echo $Arabic->ar2en($term);
array_push($result, $Arabic->ar2en($term));
}
$result=implode(",",$result);
?>
var arabic = new Array();
arabic='<?php echo $result; ?>';
alert(arabic);
});
</script>
Entire code is here : https://gist.github.com/karimkhanp/d4ac41fa864fd8ae0521
You can do one thing in this scenario to pass the variable from PHP to js. You can convert the array using json_encode() before echoing:
$result=json_encode( implode(",",$result) );
As a result, when you assign this variable to js in the <?= ?> block, it will read the json string and thus the array will be assigned:
arabic='<?php echo $result; ?>';

Categories