I'm trying to pass on a PHP array to then use the array in JavaScript.
The PHP code I'm using is as follows:
<?php
$link = mysqli_connect("localhost", "root", "password", "database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM Employees";
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
print_r($row);
/* free result set */
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($data);
?>
JavaScript:
<script>
var array = <?php echo $data; ?>;
console.log(array);
</script>
The data array in PHP doesn't seem to get passed on to the Javascript var array. When looking at the console on firebug the following error messages are displayed:
Notice - Array to string conversion.
I'd really appreciate any help as to why this error is occurring.
Maybe because you are echo'ing the array instead of the json encoded string.
Use this
<script> var array = <?php echo $json_array; ?>;
console.log(array); </script>
I believe it should be:
<script> var array = <?php echo $json_array; ?>;
console.log(array); </script>
You're using json_encode in $data but you're not using that variable in your code. Could that be it?
Related
I've got a MySQL database of offices with geo data. I'm trying to get a list of the office cities into a JavaScript array. For now, I just wanted to set up a simple $.ajax() to log the list into the console, but it's returning null. I'm just running my JavaScript function "query()" in console after the page loads.
Here's my JavaScript.
function query() {
$.ajax({
url: "query.php",
method: "POST",
dataType: 'json',
success: function(data) {
let output = JSON.parse(data)
console.log(output)
}
})
}
Here's query.php
<?php
include 'database.php';
$sql="SELECT `Office City` FROM `offices`";
$result = $link->query($sql);
if ($result) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
header('Content-type: application/json');
echo json_encode($result_array);
$link->close();
?>
Here's database.php. I'm able to write to MySQL using this PHP, so I assume it's correct.
<?php
$hostname = "hostus.mostus.com";
$username = "name";
$password = "pw";
$database = "db";
$link = mysqli_connect($hostname, $username, $password,$database);
if (mysqli_connect_errno()) {
die("Connect failed: %s\n" + mysqli_connect_error());
exit();
}
When I run query() in the console, it responds "undefined" then null.
Your sql is invalid.
I would also init the $result_array before. Currently if the result is empty, you are returning null.
<?php
include 'database.php';
$sql="SELECT `Office`, `City` FROM `offices`";
$result = $link->query($sql);
$result_array = [];
if ($result) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
header('Content-type: application/json');
echo json_encode($result_array);
$link->close();
?>
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 am making a array from values from databse in PHP then storing it into javascript array. When I alert the array the single quotes are not visible, although when PHP is seen it shows the quotes around values. What’s wrong in my code? It should be ['1','2','3','4'] but it shows [1,2,3,4].
<script>
var values = [
<?php
$conn = mysql_connect("localhost","root","") or die ("we couldn't connect!");
mysql_select_db("test_value");
$rs = mysql_query("SELECT * FROM test") or die(mysql_error());
while($row = mysql_fetch_array($rs))
{
echo "'".$row['var1']."',";
}
?>
];
window.alert(values);
</script>
<script>
var values=[
<?php
$conn =mysql_connect("localhost","root","") or die ("we couldn't connect!");
mysql_select_db("test_value");
$rs = mysql_query("SELECT * FROM test") or die(mysql_error());
while($row = mysql_fetch_array($rs)){
echo "\'".$row['var1']."\',";
}?>
];
window.alert(values);
</script>
Use this , this may help you
<script>
$(function() {
var name = [
<?php
$Database = "database name";
$DatabaseUserName = "db_user";
$DatabasePass = "db_pass";
$connect = mysql_connect("~", $DatabaseUserName, $DatabasePass);
#mysql_select_db($Database) or ("Database not found");
$query = "SELECT ~ FROM ~";
$result = mysql_query($query) or die ( $result."<br/><br/>".mysql_error());
while ($row = mysql_fetch_array($result)) {
echo "\"". $row['~']."\", ";
}
// $result = mysql_query($query) or die ( $result."<br/><br/>".mysql_error());
mysql_close($connect);
?>
];
$( "#~" ).autocomplete({
source: name
});
});
</script>
Basically, I'm getting correct output except the closing PHP tag "?>" is included in the output when I don't want it to be. Is there a better way to do this?
Use json_encode() to output JavaScript safe data. For example...
<script>
<?php
// connect, query, etc
$data = [];
while ($row = ...) {
$data[] = $row['~'];
}
?>
var name = <?= json_encode($data) ?>;
</script>
Here's a simplified demo ~ eval.in
And of course, here's the obligatory "don't use the deprecated mysql extension, etc" addendum.
Run this code and check if it is still coming. I could not reproduce the error.
<html>
<head>
<script>
var name = [
<?php
$row=array("Volvo", "BMW", "Toyota");
for($i=0;$i<count($row);$i++) {
echo "\"". $row[$i]."\", ";
}
?>
];
</script>
</head>
<body>
</body>
</html>
I have the following in my page header
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="javascript/autoSuggest.js"></script>
<script type="text/javascript" src="javascript/suggest.js"></script>
suggest.js is made of:
$(function(){
$("#idName input").autoSuggest("../Test.php", {minChars: 2, matchCase: true});
});
and autoSuggest.js is a plugin by Drew Wilson (http://code.drewwilson.com/entry/autosuggest-jquery-plugin)
Test.php is
<?php
include('database_info.inc');
$input = $_POST["idName"];
$data = array();
var_dump($data);
// query database to see which entries match the input
$query = mysql_query("SELECT * FROM test WHERE title LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['title'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>
My var_dump() doesn't do anything and no items are suggested ...what could I be doing wrong? seems like there's no communication with Test.php
A quick look at the plug-in suggests it expects a parameter called q passed as a GET string, not as a POST.
<?
$input = $_GET["q"];
$data = array();
// query your DataBase here looking for a match to $input
$query = mysql_query("SELECT * FROM my_table WHERE my_field LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['username'];
$json['image'] = $row['user_photo'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>