PHP MySQL value pass to JavaScript - 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>

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.

Putting a JavaScript variable in PHP array

I was making an image gallery with up and down buttons ,the array $imageids contains all image ids. I want to access these values with
JavaScript as follows,
PHP :
require"./connect.php";
$imgquery = mysql_query("SELECT * FROM press INNER JOIN subscriptions ON press.userid=subscriptions.to_u WHERE subscriptions.from_u='30' ORDER BY press.id DESC ");
$countrow = mysql_num_rows($imgquery);
$imageids = array();
while($fimgq = mysql_fetch_assoc($imgq)) {
$imgid = $fimgq['id'];
array_push($imageids,$imgid);
}
JavaScript:
$(document).ready(function() {
var i = -1;
var cr = <?php echo $countrow ?>;
$('#down').click(function() {
if (i < cr-1) {
i = i + 1;
var ard = <?php echo $imageids[i]?>;
alert(ard);
}
});
$('#up').click(function() {
if(i>0) {
i = i - 1;
var aru = <?php echo $imageids[i]?>;
alert(aru);
}
});
});
I want to get $imageids elements by putting a javascript variable i inside $imageids[] array , like
var ard = <?php echo $imageids[i]?>;
alert(ard); // Which doesn't work
As #chris85 and #Khalos pointed out in comments, the PHP variables are all dead once the JavaScript runs, so you need to output all the ID:s into an JavaScript array. It would looke something like this:
$(document).ready(function(){
var i=-1;
var cr= <?php echo $countrow ?>;
//Save all the ID:s to a JS variable so they can be used later.
var imageids = [<?php echo implode(',', $imageids); ?>];
$('#down').click(function(){
if(i<cr-1) {
i=i+1;
alert(imageids[i]); //This uses the JS variable imageids, not the dead PHP one.
}
});
$('#up').click(function(){
if(i>0) {
i=i-1;
alert(imageids[i]); //Same as above.
}
});
});

JSON Encode converts to null - so weird

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

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.

Saving variables within while loop

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'

Categories

Resources