I am trying to use a code that will take data from a mySQL database bind that data to a variable, put all the resulting $x into a PHP array, and finally convert it to JSON format. I then take the JSON into javascript to handle the data from the data base there.
Please see my code:
<?php
//bind to $x
$mysqli = new mysqli('localhost', 'root', 'root', 'mytable');
if ($stmt = $mysqli->prepare("SELECT x FROM data")) {
$stmt->bind_result($x);
$OK = $stmt->execute();
}
//put all of the resulting $x into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $x;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);
if ($stmt = $mysqli->prepare("SELECT data.y FROM data")) {
$stmt->bind_result($y);
$OK = $stmt->execute();
}
//put all of the resulting y into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $y;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array2 = json_encode($result_array);
?>
<script>
var xv = <?php echo $json_array; ?>;
var yv = <?php echo $json_array2; ?>;
var storage = [];
for(var i=0;i<100;i++)
{
var x = xv[i];
var y = yv[i];
var json = {x: x, y: y};
storage.push(json);
}
My question is why is the page displaying this as an output and not transferring the data to the arrays
"prepare("SELECT x FROM data")) { $stmt->bind_result($x); $OK = $stmt->execute(); } //put all of the resulting names into a PHP array $result_array = Array(); while($stmt->fetch()) { $result_array[] = $x; } //convert the PHP array into JSON format, so it works with javascript $json_array = json_encode($result_array); /* if ($stmt = $mysqli->prepare("SELECT data.y FROM data")) { $stmt->bind_result($y); $OK = $stmt->execute(); } //put all of the resulting names into a PHP array $result_array = Array(); while($stmt->fetch()) { $result_array[] = $y; } //convert the PHP array into JSON format, so it works with javascript $json_array2 = json_encode($result_array); */ ?>"
In those lines you have wrong code:
var xv = "<?php echo $json_array; ?>";
var yv = "<?php echo $json_array2; ?>";
You are printing output from json_encode into a double quoted section. This means when PHP render that page, output will be like that:
var xv = "[...smth]";
After those lines you are trying to get a value from array inside for but xv and xz variables are not type of object they are strings. Instead of this do it like that:
var xv = <?=$json_array;?>;
var yv = <?=$json_array2;?>;
The xv and yv is a string since you used json_encode.
You can use JSON.parse to convert the string into json.
var xv = "<?php echo $json_array; ?>";
xv = JSON.parse(xv);
var yv = "<?php echo $json_array2; ?>";
yv = JSON.parse(yv);
var storage = [];
for(var i=0;i<100;i++)
{
var x = xv[i];
var y = yv[i];
var json = {x: x, y: y};
storage.push(json);
}
First: if you're seeing PHP code in your output, you need to check your server and PHP configuration. Your PHP script is being interpreted by the web server as plain text and just spitting out the raw code instead of executing it through the PHP interpreter.
Second: embedding PHP in Javascript is less than ideal. You should have a PHP script to handle the MySQL querying, then fetching the output in Javascript with an AJAX request. Additionally, the way you're mutating the data is redundant and suboptimal.
This will retrieve your results from the database and encode it as JSON:
<?php
// connect, query, bind results
$result = [];
$mysqli = new mysqli('localhost', 'user', 'pass', 'db');
if ($stmt = $mysqli->prepare("SELECT x,y FROM table")) {
$stmt->execute();
$stmt->bind_result($x,$y);
while ( $stmt->fetch() ) {
$result[] = [
'x' => $x,
'y' => $y
];
}
echo json_encode($result);
}
?>
This is a basic AJAX example to retrieve the output from the PHP script:
<script>
function fetchMyStuff() {
// basic ajax example
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if ( xhr.readyState == 4 ) {
console.log(
JSON.parse( xhr.responseText )
);
}
}
xhr.open('GET', 'myscript.php', true);
xhr.send();
}
fetchMyStuff();
</script>
You'll see the resulting object in the console corresponding to your query results:
[{x:'x1':y:'y1'},{x:'x2',y:'y2'},...]
Personally, I don't like the limitations of prepared statements and would prefer a much more optimized approach for my PHP file:
<?php
$mysqli = new mysqli('localhost', 'user', 'pass', 'db');
echo json_encode(
$mysqli->query("SELECT x,y FROM table")->fetch_all( MYSQLI_ASSOC )
);
?>
This leverages the mysql-nd module to perform all the work of fetching the full result set as an associative array and encoding it in only a few lines.
Related
I want to pass an array from PHP to Javascirpt so I just get a list of values - currently I get JSON format - which I know because I'm using JSON_ENCODE I'm just hoping/wondering is there a way to pass it as a simple set of values or to parse it afterwards?
Apologies I'm quite new to this :)
I've tried a few different things from previous answers to similar questions, but none seem to do the trick.
<?php
$user = 'xxx';
$pass = 'xxx';
$connection_string = 'connectionstringtomysqldatabase';
$connection = odbc_connect( $connection_string, $user, $pass );
$sqlstring = "SELECT FIELD1 FROM TABLE.ITEM where IASOHQ<>0 FETCH FIRST 10 ROWS ONLY";
$result = odbc_exec($connection, $sqlstring);
while ($info = odbc_fetch_array($result)) {
$content[] = $info;
}
?>
<script type="text/javascript">
var content = <?php echo json_encode($content); ?>;
</script>
I want...
var content = [68,116,49,57,13,11,46,47,14,79]
I get...
var content = [{"FIELD1":"68"},{"FIELD1":"116"},{"FIELD1":"49"},{"FIELD1":"57"},{"FIELD1":"13"},{"FIELD1":"11"},{"FIELD1":"46"},{"FIELD1":"47"},{"FIELD1":"14"},{"FIELD1":"79"}];
You are getting this result because your array is multi-dimensional with associative second level keys i.e. it looks like
$content = [['FIELD1' => 68], ['FIELD1' => 116], ..., ['FIELD1' => 79]];
This is because odbc_fetch_array returns an associative array for each row. To fix your data format, just change this line:
$content[] = $info;
to
$content[] = $info['FIELD1'];
That will give you an array that looks like your desired result of
[68,116,49,57,13,11,46,47,14,79]
Just add ' to make it a value. Change
var content = <?php echo json_encode($content); ?>;
to
var content = '<?php echo json_encode($content); ?>';
var myObject = JSON.parse(content);
Iterate over the array then.
Just change this peace of php code. I think that all of the index of array is FIELD1
...
while ($info = odbc_fetch_array($result)) {
$content[] = $info['FIELD1'];
}
...
Just
echo json_encode(array_values($content));
it will work;
This question already has answers here:
Convert php array to Javascript
(21 answers)
Closed 3 years ago.
I'm trying to convert a PHP array to a javascript array for jQuery's datetimepicker to disable some dates. But I can't seem to find the right answer on the internet. I'm using Zend Framework for my project.
<?php
$ConvertDateBack = Zend_Controller_Action_HelperBroker::getStaticHelper('ConvertDate');
$disabledDaysRange = array();
foreach($this->reservedDates as $dates) {
$date = $ConvertDateBack->ConvertDateBack($dates->reservation_date);
$disabledDaysRange[] = $date;
}
?>
<script>
var disabledDaysRange = $disabledDaysRange ???? Please Help;
$(function() {
function disableRangeOfDays(d) {
for(var i = 0; i < disabledDaysRange.length; i++) {
if($.isArray(disabledDaysRange[i])) {
for(var j = 0; j < disabledDaysRange[i].length; j++) {
var r = disabledDaysRange[i][j].split(" to ");
r[0] = r[0].split("-");
r[1] = r[1].split("-");
if(new Date(r[0][2], (r[0][0]-1), r[0][1]) <= d && d <= new Date(r[1][2], (r[1][0]-1), r[1][1])) {
return [false];
}
}
}else{
if(((d.getMonth()+1) + '-' + d.getDate() + '-' + d.getFullYear()) == disabledDaysRange[i]) {
return [false];
}
}
}
return [true];
}
$('#date').datepicker({
dateFormat: 'dd/mm/yy',
beforeShowDay: disableRangeOfDays
});
});
</script>
To convert you PHP array to JS , you can do it like this :
var js_array = [<?php echo '"'.implode('","', $disabledDaysRange ).'"' ?>];
or using JSON_ENCODE :
var js_array =<?php echo json_encode($disabledDaysRange );?>;
Example without JSON_ENCODE:
<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
?>
var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];
alert(js_array[0]);
</script>
Example with JSON_ENCODE :
<script type='text/javascript'>
<?php
$php_array = array('abc','def','ghi');
?>
var js_array =<?php echo json_encode($disabledDaysRange );?>;
alert(js_array[0]);
</script>
The PHP json_encode function translates the data passed to it to a JSON string which can then be output to a JavaScript variable.The PHP json_encode function returns a string containing the JSON equivalent of the value passed to it.
<?php
$ar = array('apple', 'orange', 'banana', 'strawberry');
echo json_encode($ar); // ["apple","orange","banana","strawberry"]
?>
You can pass the JSON string output by json_encode to a JavaScript variable as follows:
<script type="text/javascript">
// pass PHP variable declared above to JavaScript variable
var ar = <?php echo json_encode($ar) ?>;
</script>
A numerically indexed PHP array is translated to an array literal in the JSON string. A JSON_FORCE_OBJECT option can be used if you want the array to be output as an object instead:
<?php
echo json_encode($ar, JSON_FORCE_OBJECT);
// {"0":"apple","1":"orange","2":"banana","3":"strawberry"}
?>
Associative Array Example:
<?php
$book = array(
"title" => "JavaScript: The Definitive Guide",
"author" => "David Flanagan",
"edition" => 6
);
?>
<script type="text/javascript">
var book = <?php echo json_encode($book, JSON_PRETTY_PRINT) ?>;
/* var book = {
"title": "JavaScript: The Definitive Guide",
"author": "David Flanagan",
"edition": 6
}; */
alert(book.title);
</script>
Notice that PHP's associative array becomes an object literal in JavaScript. We use the JSON_PRETTY_PRINT option as the second argument to json_encode to display the output in a readable format.
You can access object properties using dot syntax, as displayed with the alert included above, or square bracket syntax: book['title'].
here you can find more information and details.
When we convert PHP array into JS array then we get all values in string.
For example:
var ars= '<?php echo json_encode($abc); ?>';
The issue in above method is when we try to get the first element of ars[0] then it gives us bracket where as in we need first element as compare to bracket so the better way to this is
var packing_slip_orders = JSON.parse('<?php echo json_encode($packing_slip_orders); ?>');
You should use json_parse after json_encode to get the accurate array result.
Have you tried using json_encode http://php.net/manual/en/function.json-encode.php
It converts an array to a json string
This may be a easy solution.
var mydate = '<?php implode("##",$youdateArray); ?>';
var ret = mydate.split("##");
<?php
$ConvertDateBack = Zend_Controller_Action_HelperBroker::getStaticHelper('ConvertDate');
$disabledDaysRange = array();
foreach($this->reservedDates as $dates) {
$date = $ConvertDateBack->ConvertDateBack($dates->reservation_date);
$disabledDaysRange[] = $date;
}
$disDays = size($disabledDaysRange);
?>
<script>
var disabledDaysRange = {};
var disDays = '<?=$disDays;?>';
for(i=0;i<disDays;i++) {
array.push(disabledDaysRange,'<?=$disabledDaysRange[' + i + '];?>');
}
............................
<script> var disabledDaysRange = $disabledDaysRange ???? Please Help;
$(function() {
function disableRangeOfDays(d) {
in the above assign array to javascript variable "disableDaysRange"
$disallowDates = "";
echo "[";
foreach($disabledDaysRange as $disableDates){
$disallowDates .= "'".$disableDates."',";
}
echo substr(disallowDates,0,(strlen(disallowDates)-1)); // this will escape the last comma from $disallowDates
echo "];";
so your javascript var diableDateRange shoudl be
var diableDateRange = ["2013-01-01","2013-01-02","2013-01-03"];
<?php
$ConvertDateBack = Zend_Controller_Action_HelperBroker::getStaticHelper('ConvertDate');
$disabledDaysRange = array();
foreach($this->reservedDates as $dates) {
$date = $ConvertDateBack->ConvertDateBack($dates->reservation_date);
$disabledDaysRange[] = $date;
array_push($disabledDaysRange, $date);
}
$finalArr = json_encode($disabledDaysRange);
?>
<script>
var disabledDaysRange = <?=$finalArr?>;
</script>
You should need to convert your PHP array to javascript array using PHP syntax json_encode.
json_encode convert PHP array to JSON string
Single Dimension PHP array to javascript array
<?php
var $itemsarray= array("Apple", "Bear", "Cat", "Dog");
?>
<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[2]); // Output: Bear
// OR
alert(items[0]); // Output: Apple
</script>
Multi Dimension PHP array to javascript array
<?php
var $itemsarray= array(
array('name'='Apple', 'price'=>'12345'),
array('name'='Bear', 'price'=>'13344'),
array('name'='Potato', 'price'=>'00440')
);
?>
<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[1][name]); // Output: Bear
// OR
alert(items[0][price]); // Output: Apple
</script>
For more detail, you can also check php array to javascript array
How can i insert PHP db result query to a javascript array. I have set of values in my Database and I want to get those values and store it in a javascript array. This is my query
$query = $db->query("SELECT * FROM members");
while ($row = $query->fetch_assoc()) {
echo $row['names'];
}
And I want to store it in a javascript array like this
var names = ['John','Chris','Leo'];
This is my code but im getting an error.
var names = [
<?php while ($row = $query->fetch_assoc()) {
echo $row['skill'];
} ?>
];
Do this instead.
$names = [];
<?php while ($row = $query->fetch_assoc()) {
$names[] = $row['skill'];
}
$javaScriptArray = json_encode($names);
?>
JavaScript is run on the browser while PHP is run on the server. They don't really integrate with each other. To make the array available in javascript do something like this.
<script>
var arr = <?php echo $javaScriptArray; ?>;
</script>
I am unable to find a simple and elegant solution to solve this after several tries.
In essence I would like a way to fetch the 5 fields taken from this query and assign them to PHP variables then latterly Javascript variables.
<?php
include_once('connect.php');
$result = mysqli_query($conn, " SELECT DISTINCT IPdestport as destport,COUNT(*) as count FROM PACKETSFORIP GROUP BY destport ORDER BY count DESC LIMIT 5;");
while($row[] = mysqli_fetch_array($result))
{
$destport1 = $row[1][ 'destport' ];
$destport2 = $row[2]['destport'];
$destport3 = $row[3]['destport'];
$destport4 = $row[4]['destport'];
$destport5 = $row[5]['destport'];
$count1 = $row[1]['count'];
$count2 = $row[2]['count'];
$count3 = $row[3]['count'];
$count4 = $row[4]['count'];
$count5 = $row[5]['count'];
}
?>
Here is more code of how I will eventually translate these PHP variables into Javascript variables in order to process them into a google chart
var destport1 = "<?php echo $destport1 ?>";
var destport2 = "<?php echo $destport2 ?>";
var destport3 = "<?php echo $destport3 ?>";
var destport4 = "<?php echo $destport4 ?>";
var destport5 = "<?php echo $destport5 ?>";
var count1 = "<?php echo $count1 ?>";
var count2 = "<?php echo $count2 ?>";
var count3 = "<?php echo $count3 ?>";
var count4 = "<?php echo $count4 ?>";
var count5 = "<?php echo $count5 ?>";
Any help would be very much appreciated. Thanks.
You can save a lot of repetitive code by using arrays.
To simplify the first step (assign them to PHP variables) just convert the result set into an array:
$destPorts = mysqli_fetch_all($result);
$destPorts will contain all of the rows from the result set. If you want to access the 'count' column of the second row, use:
$destPorts[1]['count']
Or to access the 'destport' column of the fourth row, use:
$destPorts[3]['destport']
Since the values are stored in the $destPorts array, there is no need to convert them into separate variables.
You can do something similar in JavaScript. Instead of creating separate variables, store the data in a JavaScript object:
var destPorts = <?php echo json_encode($destPorts); ?>
Now you can access the values stored in the destPorts JavaScript variable. To access the 'count' column of the second row, use:
destPorts[1].count
Or to access the 'destport' column of the fourth row, use:
destPorts[3].destport
When you store your result rows in arrays and objects instead of simple numerically indexed variables, your code is less repetitive and more flexible. You no longer need to know how many results are in the database; you can simply loop over the array or object and access all of the data.
For anyone searching for this in future this is the solution i eventually utilised. Found it in a previous web application i'd coded.
<?php
include_once('connect.php');
$result = mysqli_query($conn, " SELECT DISTINCT IPdestport as destport,COUNT(*) as count FROM PACKETSFORIP GROUP BY destport ORDER BY count DESC LIMIT 5;");
$portsarray = Array();
$countarray = Array();
while($row = mysqli_fetch_array($result))
{
$portarray[] = array('destport'=>$row['destport'], 'count'=>$row['count']);
echo $row['count'];
}
$portarray = json_encode($portarray);
?>
The above code fetches each port and the count of packets going to that port and this is latterly converted into javascript to be fed into a google chart, but i'll just show the part that fetches the PHP array and puts the variables contained within into javascript variables.
var obj = <?php echo $portarray; ?>;
for(var i= 0; i < obj.length; i++) {
var json = obj[i];
destport = json.destport;
numberofpackets = json.count;
destport = destport.toString();
numberofpackets= parseInt(numberofpackets);
I have a multidimensional array in php, and i want to get its data from javascript but i didn't work
here my code in php
$managername = $_SESSION['managername'];
$sqls = "select s.*,m.* from rm_allowedmanagers m inner join rm_services s on s.srvid = m.srvid where m.managername = '$managername' ";
$sql = mysql_query($sqls);
$newservices = array();
while($row = mysql_fetch_array($sql))
{
$nsrvid = $row['srvid'];
$nsrvname = $row['srvname'];
$nunitprice = $row['unitprice'];
$nunitpricetax = $row['unitpricetax'];
$ntotal = $nunitprice + $nunitpricetax;
$newservice = array($nsrvid, $nsrvname , $ntotal);
array_push ($newservices, $newservice);
}
and here my java script code
<script>
function changeserviceprice(id)
{
var newservice = $("#newservice").val();
var data = '<?= $newservices ?>';
var asd = data;
var asd2 = data[0][0];
$("#qq4").val(asd);
$("#qq5").val(asd2);
}
</script>
PHP code i think it is work fine, and i think the error is in javascript function.
when i try to print the data using javascript it print the "Array" word when i print the whole row "array", but
it print "a" character when i try to print the first element in the first array!!
try encoding the $newservices array:
var data = <?php echo json_encode($newservices); ?>;