JSON Encode converts to null - so weird - javascript

This is the weirdest thing i've seen. I have an array that I created with php - then I used JSON_Encode to use it with a FLOT Graph. I echoed out the encoded array once - and it's perfect.
Then randomly, another alert box appears with "null".
Subsequently, the script also has a "null" when i echo it into the javascript.
the var d1 is null when I inspect it...
At first I get an alert box with [[0,50],[1,3],[2,488],[3,25],[4,90],[5,50],[6,90],[7,50],[8,5]] -- then I get a second alert box WHICH I DID NOT CODE with "null".
code:
<?php
$num = 0;
while($row = $sql->fetch(PDO::FETCH_OBJ)){
$line[] = array($num,intval($row->percent));
$num ++;
}
$TEST = json_encode($line);
echo "<script>alert('".$TEST."');</script>";
?>
<script>
var d1 = <?php echo $TEST;?>;
$(document).ready(function () {
$.plot($("#chart"), [d1]);
});
</script>
Output from Inspector:
var d1 = []; //Notice the empty array
$(document).ready(function () {
$.plot($("#chart"), [d1]);
});

Use $line = array(); for empty data from while loop
$line = array();
while(....
You can check empty
if(count($line)!=0) {
$TEST = json_encode($line);
echo "<script>alert('".$TEST."');</script>";
}
UPDATE:
$TEST = json_encode($line);
echo "<script>$.plot($('#chart'), \"<?php echo $TEST; ?>\");</script>";

Related

passing array data from PHP to Javascript

I am fetching an array from a MySQL result into a array variable. I can successfully use a simple php echo line in the javascript beneath to grab the first $row element, but I want to use json_encode to get the whole array at once.
When I do this and try to set a javascript var to the first array element something goes wrong and even the single var method stops working.
<?php
.
.
.
while($row = $result->fetch_array(MYSQLI_NUM)) {
$row1 = $row[0];
}
?>
<script type="text/javascript">
var RowArray = <?php echo json_encode($row); ?>;
var RA1 = RowArray[0];
window.alert(RA1);
var Row1 = '<?php echo $row1; ?>';
window.alert(Row1);
</script>
Make an array containing all the records:
$rows = [];
while ($row = $result->fetch_array(MYSQLI_NUM))
{
// do custom modifications to $row if neededed
$rows[] = $row; // push to array
}
Or just:
$rows = $result->fetch_all(MYSQLI_NUM);
And then use json_encode() with $rows.

PHP MySQL value pass to JavaScript

hei,
$i=0;
while($row = $result->fetch_assoc()) {
echo "
<tr><td>".$row["Number"]."</td><td>".$row["MusikName"]." ".$row["MusikURL"]."</td></tr>";
this part works...it give me -> 1 test1 url1.de 2 test2 url2.de ...
So what I want is to pass the URL to a JavaScript Array...by doing in phpscript
$urlarray[]=$row["MusikURL"];
echo $urlarray[$i]; // gives me url1.de url2.de url3.de
i++; // to fill $urlarray[1] [2] [...] with urls
How do I pass the urls to a JavaScript Array so that I can access to those by
javascriptarrayurl[1] javascriptarrayurl[2] (result should be a clear url) ... I got troubles with JSON :c
thanks in advance !!
You can use jQuery and have something like
<?php
$returnArray = array();
while ($row = $result->fetch_assoc()) {
array_push($returnArray, $row);
}
$jsonArray = json_encode($returnArray);
?>
<script>
$(document).ready(function () {
var objArray = $.parseJSON("<?php echo $jsonArray; ?>");
for (var i = 0; i < objArray.length; i++) {
var row = objArray[i];
console.log(row);
// Now here you have access to row.Number row.MusikURL
}
});
You can use json_encode() to convert a PHP variable to its Javascript literal notation.
<script>
var urlarray = <?php echo json_encode($urlarray); ?>;
</script>

php array not showing up in javascript

I created an array of values from data in MySQL. I then try to print it in Javascript but unfortunately it is not showing up.
Database has two cols: gurtej and singh
<?php
require_once('config.php');
function readAttribute($connect){
$resultArray=array();
$sql="SELECT Attributename,Entityname FROM temp_data_attribute";
$res=mysqli_query($connect,$sql);
echo mysqli_num_rows($res);
if(mysqli_num_rows($res)==0){
return 0;
}
else{
while($result=mysqli_fetch_array($res)){
array_push($resultArray,$result[0]);
}
return $resultArray;
}
}
?>
<html>
<body>
<script>
var jArray= <?php
$resultArray=readAttribute($connect);
if($resultArray==0){
$resultArray=[];
}
echo json_encode($resultArray);?>;
var counter=<?php echo count($resultArray);?>;
document.write(jArray[0]);
</script>
<?php
print_r($resultArray);
?>
</body>
</html>
And when i try to print it in php using print_r this is the result.
Array ( [0] => gurtej [1] => singh )
The resulting JavaScript statement includes more than just the var and array as JSON:
var jArray = 2["gurtej","singh"];
The extra 2 comes from the echo within readAttribute() showing the number of rows:
function readAttribute($connect){
$resultArray=array();
$sql="SELECT Attributename,Entityname FROM temp_data_attribute";
$res=mysqli_query($connect,$sql);
echo mysqli_num_rows($res);
// ^^^^
By following the number, the "array" changes meaning and is interpreted as a bracket property accessor with a comma operator. The statement behaves the same as:
var jArray = (2).singh;
And, the number 2 doesn't (normally) have a property named singh. So, you get undefined, which can't have properties.
console.log(typeof jArray); // 'undefined'
console.log(jArray[0]); // TypeError
To remove the 2, you'll want to remove or comment out the additional echo:
function readAttribute($connect){
$resultArray=array();
$sql="SELECT Attributename,Entityname FROM temp_data_attribute";
$res=mysqli_query($connect,$sql);
// echo mysqli_num_rows($res);
// ...
}
var jArray = ["gurtej","singh"];
console.log(typeof jArray); // "object"
console.log(jArray[0]); // "gurtej"
Let's clean up that function a bit and we'll fix the problem too
function readAttribute($connect){
$resultArray = array();
$sql="SELECT Attributename,Entityname FROM temp_data_attribute";
$res=mysqli_query($connect,$sql);
//echo mysqli_num_rows($res);
while($result = mysqli_fetch_assoc($res)){
$resultArray[] = $result;
}
return $resultArray;
}
Your problem is that you were using $result[0], but that just pushes the first column. And if you're going to json_encode this, I would avoid using fetch_array() (without an argument) because it returns both a numeric AND associative key value for each column (which will inflate your data set of rows)
Lets clean up the code:
<html>
<body>
<!-- container to hold data -->
<div id='container'></div>
<script>
<?php
//--- get the results from the database
$resultArray=readAttribute($connect);
//--- convert if necessary
if($resultArray==0){
$resultArray=[];
}
?>;
//--- place results into JavaScript array
var jArray= <?php echo json_encode($resultArray);?>;
//--- show the raw array
document.getElementById('container').innerHTML = jArray[0];
</script>
<?php
print_r($resultArray);
?>
</body>
</html>

Getting my dynamic php array to js

Here's what I got
$x=$ris;
while ($x<$rie){
array_push($array, pg_fetch_result($result,$x,0));
$x=$x+1;
}
So I'm just pushing lot's of values from a column to $array. I want to transmit the data in this array to a js array. So here's what's happening:
<script>
var temp = <?php echo json_encode($rie-$ris); ?>;
var temp2=0;
var jarray = [];
while (temp2<temp)
{
jarray.push(<?php echo json_encode($array[temp2]); ?>);
temp2++;
}
console.log(jarray)
</script>
Whenever I try to print anything out, jarray has nothing in it, which leads me to think that this
jarray.push(<?php echo json_encode($array[temp2]); ?>);
line is messed up. It's probably because I'm trying to reference a js variable in a php echo. The problem is I'm trying to make a while loop to just copy the array over, but in js, I'm incrementing a js var, so how can I possibly do this?
Try my code. First json_encode your php array and then JSON.parse in js after that while loop.
<script>
var temp = <?php echo json_encode($rie-$ris); ?>;
var temp2=0;
var jarray = [];
var arr = '<?php echo json_encode($array); ?>';
var arr_p = JSON.parse(arr);
while (temp2<temp)
{
jarray.push(arr_p[temp2]);
temp2++;
}
console.log(jarray)
</script>

adding php array values to javascript array

I have a php array and I want to add its value to a javascript array. For example I am doing it something like this.
$k_data = json_encode($k)
Thus
k_data = [2,3,4,8,9]
Now in javascript I am doing like the following
var s4 = [[]];
for(var i = 0; i<5; i++)
{
s4.push([i,$k_data[i]]);
}
plot5.series[0].data = s4;
where plot5 is jqplot graph. But this is not working, I am getting blank graph while the following thing is working
for(var i = 0; i<5; i++)
{
s4.push([i,Math.sin(i)]);
}
Where I am making mistake?
If you want to deal with the php array only, you can do this-
First, implode the array to make a comma-separated string, say $str. Just like-
<?php
$str = implode(",", $array);
?>
Then, use split to convert the php string to the javascript array. Just like-
<script>
var str = <?php echo $str; ?>;
var array = str.split(',');
</script>
OR, json_encode() can help you directly-
<script>
<?php
$js_array = json_encode($php_array);
echo "var js_array = ". $js_array . ";\n";
?>
</script>
Well you can do a for loop and echo the Javascript commands to fill the Javascript Array
<script>
var s4 = [[]];
<?php
$k_data = json_encode($k)
$i = 0;
foreach($k_data as $v) {
echo 's4.push([' , $i , ',Math.sin(' , $v , ')]);';
++$i;
}
?>
plot5.series[0].data = s4;
</script>
It seems that you are refering to a php variable in you javascript. Keep in mind that PHP is executed serverside, whereas javascript is executed by the browser. Therefore, you need to pass the PHP variable to your javascript. Assuming that your javascript and PHP are in one .php file, replacing above javascript with the following should work:
<?php $k_data_js = implode("','", $k_data); ?>
var k_data = <?php echo "['" . $k_data_js . "']"; ?>;
var s4 = [[]];
for(var i = 0; i<k_data.length; i++)
{
s4.push([i,k_data[i]]);
}
plot5.series[0].data = s4;
The variable is passed to javascript in the second line. From then on you can refer to k_data in your script.

Categories

Resources