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.
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>
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 6 years ago.
I'm having problems with the following loop, which generates null results for the variable newLat[i]. However, when I directly populate newLat[0] (in the last 2 lines) it works fine. Any thoughts?
PHP:
$sql = "SELECT `id`, `name`, `lat`, `lng` FROM `markers` " ;
$result = $dbc->query($sql);
$hits = $result->num_rows ;
echo "<br /> Records = " ;
echo "$hits <br />";
while($row = $result->fetch_assoc()) {
$MarkerID[] = $row['id'];
$MarkerName[] = $row['name'];
$MarkerLat[] = $row['lat'];
$MarkerLng[] = $row['lng'];
}
and Javascript:
var myhits = <?php echo json_encode($hits); ?>;
var newLat = new Array (myhits);
for (var i = 0; i < myhits; i++) {
newLat[i] = <?php echo json_encode($MarkerLat[i]); ?>;
document.write (newLat[i]);
}
newLat[0] = <?php echo json_encode($MarkerLat[0]); ?>;
document.write (newLat[0]);
for (var i = 0; i < myhits; i++) {
newLat[i] = <?php echo json_encode($MarkerLat[i]); ?>;
document.write (newLat[i]);
}
You're trying to include PHP code in your JavaScript loop. This is simply impossible, as all PHP is evaluated on the server, while JS is on the client. Open your webpage and "view source" -- you'll see there probably isn't anything on that line.
You'll have to figure out another way to do this; perhaps send $MarkerLat to the client the same way you do hits.
You can't use a FOR pointer inside a different language block:
for (var i = 0; i < myhits; i++) {
newLat[i] = <?php echo json_encode($MarkerLat[i]); ?>;
document.write (newLat[i]);
}
You are trying to use a JavaScript i inside a PHP block. Not only has the PHP block executed by this point, it wouldn't know what to do with that i. It will be 0.
You need to dump the contents of $MarkerLat[i] into a JavaScript array before running it through your loop.
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>
I know this topic was already discussed a few times but I can't seem to find what I'm doing wrong.
What I'm trying to do:
The user types in a number and by clicking on the button creates a table with that number of columns.
Heres the php:
<?php
$twig = require_once('bootstrap.php');
$hostname = 'localhost';
$username = 'root';
$password = '';
$conn = new PDO("mysql:host=$hostname;dbname=mydb", $username, $password);
echo $twig->render('index.html', array());
$numOfRows = 1;
if(isset($_POST['button'])){
$numOfRows = $_POST['num_input'];
}
html/javascript:
<html>
<head>
<script>
function insertRows(){
var numOfRows = <?php echo json_encode($numOfRows) ?>;
var out = "<table><tr><th>test</th>";
for (i = 0; i < numOfRows; i++){
out += "<th>test</th>";
}
out += "</tr></table>";
document.getElementById("table").innerHTML = out;
}
</script>
</head>
<body>
<form action="index.php" method="post">
<textarea id="num_input" name ="num_input"></textarea>
<button type="button" name="button" onclick="insertRows()"> Go </button>
</form>
<p id="table"></p>
</body>
</html>
Theres no error or anything since I'm not using a IDE, just doing it in vim but the error is that is just doesn't happen. If i change "numOfRows" in the for loop to a number it works, so I'm pretty sure the json_encode is the problem.
Thanks!
EDIT:
Just to test it, I used a string variable $str = "test"; the php file, and instead of using the for loop, I just edited javascript to
var str = <?php echo json_encode($str); ?>;
alert(str);
and I also tried
var str = <?php echo $str; ?>;
alert(str);
but nothing works.
json_encode is not necessary in this case.
Simply replace
var numOfRows = <?php echo json_encode($numOfRows); ?>;
with
var numOfRows = <?php echo (int)$numOfRows; ?>;
Edit: You are missing a ; on the
<?php echo json_encode($numOfRows) ?>
Should be
<?php echo json_encode($numOfRows);?>
And in these cases, if would be good to check the server log, this will automaticly make you better at finding these mistakes yourself.
You are mixing up ints and strings. The database will in PHP always return strings and the way you are using the variable as an int in a for loop.
The following change i believe would achieve the right result.
$numOfRows = intval($_POST['num_input']);
Where you use PHP's conversion to integer function there is at a global level.
You did not forget any $. JS does not need $ for variables.
As far as your json_encode is concerned, if you are just passing an integer from PHP to JS, there is no need to json_encode. Just pass the variable to JS as <?=$numOfRows?> in the JS source.
This is part of my code to display an album on my page. If I call the function like this
<?php
for ($key_Number = 0; $key_Number < count($album); $key_Number++) {
echo 'Gallery1<br>';
}
?>
<script type="text/javascript">ajax_json_gallery('gallery1');</script>
It works fine. gallery1 is a file on my server with test photos inside. If I call it like this
<?php
for ($key_Number = 0; $key_Number < count($album); $key_Number++) {
echo ''.$album[$key_Number].'<br>';
}
?>
<script type="text/javascript">ajax_json_gallery($album[$key_Number]);</script>
It doesn't work. What am I doing wrong? Any ideas?
I need to pass different strings depending on the user so I need to give it a variable.
And yes, my array $album does contain the correct file folder names.
Here is the function that is called.
<script type="text/javascript">
function ajax_json_gallery(folder){
var thumbnailbox = document.getElementById("thumbnailbox");
var pictureframe = document.getElementById("pictureframe");
var hr = new XMLHttpRequest();
hr.open("POST", "json_gallery_data2.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var d = JSON.parse(hr.responseText);
pictureframe.innerHTML = "<img src='"+d.img1.src+"'>";
thumbnailbox.innerHTML = "";
for(var o in d){
if(d[o].src){
thumbnailbox.innerHTML += '<div onclick="putinframe(\''+d[o].src+'\')"><img src="'+d[o].src+'"></div>';
}
}
}
}
hr.send("folder="+folder);
thumbnailbox.innerHTML = "requesting...";
}
function putinframe(src){
var pictureframe = document.getElementById("pictureframe");
pictureframe.innerHTML = '<img src="'+src+'">';
}
And here is the page that gets the photos json_gallery_data2.php
<?php
header("Content-Type: application/json");
$folder = $_POST["folder"];
$jsonData = '{';
$dir = $folder."/";
$dirHandle = opendir($dir);
$i = 0;
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && preg_match("/.jpg|.gif|.png/i", $file)){
$i++;
$src = "$dir$file";
$jsonData .= '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
}
}
closedir($dirHandle);
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
?>
This is mixing server-side and client-side code:
ajax_json_gallery($album[$key_Number]);
The variables $album and $key_number aren't defined in JavaScript, so it can't use them. (I'm sure when it's "not working" it's actually telling you on the JavaScript console that those variables aren't defined.)
To emit values from PHP, you need to surround them with <?php ?> tags. Additionally, since it's a string in JavaScript, it needs to be enclosed in quotes in the JavaScript. Something like this:
ajax_json_gallery('<?php echo $album[$key_Number]; ?>');
1st:
$key_Number varibale on your server in the line:
<script type="text/javascript">ajax_json_gallery($album[$key_Number]);</script>
Contains count($album) value, which not exists in the array.
2nd:
If you trying to output php value in this line:
<script type="text/javascript">ajax_json_gallery($album[$key_Number]);</script>
Then try to enclose output in <?php ?> tags:
<script type="text/javascript">ajax_json_gallery('<?php echo $album[$key_Number]; ?>');</script>
3rd:
Single quotes does not allow to parse variables in string.
echo ''.$album[$key_Number].'<br>';
This ^ line doing not what you expecting.
Try to use double quotes:
echo "{$album[$key_Number]}<br>";