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.
Related
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>
I fetch some information from DB - shown here:
$link = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$handle = $link->prepare("SELECT dropAddress FROM mv_bookingEst WHERE userID='$userID'");
$handle->execute();
$result = $handle->fetchAll(\PDO::FETCH_OBJ);
//print_r($result);
$x = 0;
foreach($result as $obj){
$resultArray[$x] = $obj->dropAddress;
$x++;
}
and then in my javscript:
var count = "<?php echo json_encode($resultArray); ?>";
However I get the following error:
Syntax error: unexpected number -->
var count = "["-33.8935642, 151.20227810000006","-33.857653, 151.20853699999998 ...
If I replace json_encode($resultArray) with echo ($resultArray[0]) the values pass fine. Not sure how to fix it because everything I've read uses this method. TIA
var count = "<?php echo json_encode($resultArray); ?>";
You are returning the result of the json_encode inside of a JavaScript string. Your syntax error shows this:
Syntax error: unexpected number --> var count = "["-33.8935642, 151.20227810000006","-33.857653, 151.20853699999998 ...
Unless there's a failure in coversion, json_encode returns valid JavaScript syntax, so you should just use it as-is without any adornments in your javascript:
var count = <?php echo json_encode($resultArray); ?>;
If you want to take into consideration the possibility of failure, then you can use this instead:
var count = <?php
$tmp = json_encode($resultArray);
echo ($tmp === false ? 'null' : $tmp);
?>;
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>
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>";
not pretty sure how you do this. But I want to save my javascript variables as data(1,2,3,4,...) in my while loop. Happy for any help! Thanks
$id = 0;
while($rows = mysql_fetch_array($data)){
$id = $id + 1;
$data = $rows['data'];
?>
<script>
var id = '<?php echo $id; ?>'; //1,2,3,4,5,6,...
var data = '<?php echo $id; ?>'; // Example - Data 1 = Frog, Data 2 = Bird
// So here I want to sava variables so the name will be
// var "data+'id'";
// And the output is data for that row
</script>
<?php
}
?>
//And here outside I want to use the variables like this:
document.write(data1); writes out "Frog"
document.write(data2); writes out "Pig"
<script>
var jsData = [];
<?php
$id = 0;
while($rows = mysql_fetch_array($data)){
$data = $rows['data'];
?>
jsData[<?php echo $id; ?>] = '<?php echo $data; ?>';
<?php
$id++;
}
?>
</script>
This would yield a JS Array called jsData where your ID is the index and which is filled with the PHP $data values.
Declare $data = new Array(); just before the WHILE LOOP then in the WHILE LOOP you could do $data['id'][$id]= $id which will collect all the IDS.
Add $data['data'][$id]= $row['data'] below it so as also to collect each data that you want.
in the script tag do this:
var id = <?php echo '['.join(',', $data['id']).']' ?> //will create --> [1,2,3,4,5,6,7]
var data = <?php echo '['.join(',', $data['data']).']' ?> //--> ['cat', 'dog', 'cow', 'sheep']
now you can access the variable in the Javascript array created eg. $data[0] // 'cat'