I am trying to get the values of PHP Array in JavaScript variable.
Here is my code:
$qry="select * from optin";
$rlt1=mysql_query($qry);
$em_ary=array();
while($row= mysql_fetch_array($rlt1)){
$em_ary=$row;
echo $em_ary['timer'];}// this echo show all records that I have in data base and I want to get all the values in Javascript
<script>
var tmr=[];
tmr='<?php echo json_encode($em_ary['timer']); ?>';
alert(tmr);// this alert only shows the last record in the database
<?script>
Where I am going wrong or is there any other way to accomplish this?
Thanks in advance!
You need to update this line:
$em_ary = $row;
and change it to:
$em_ary[] = $row;
You are overwriting the array each time you want to add a new element to it.
Then, in the JS part, update this line:
tmr = '<?php echo json_encode($em_ary['timer']); ?>';
to:
tmr = JSON.parse('<?php echo json_encode($em_ary); ?>');
Hope this helps! Cheers!
You are overwriting values within your $em_ary array in order to make an array of values you need to place [] after $em_ary which will result you an array
$em_ary[]=$row;
You need to update this also from
tmr='<?php echo json_encode($em_ary['timer']); ?>';
into
tmr="<?php echo json_encode({$em_ary['timer']}); ?>";
Related
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 3 years ago.
I am familiar with php but still learning Js. Some people helped me on completing a ajax form to send data to mysql. But now I am stuck on below:
I used while loop as I want to print every thing which matches query
while($row = mysqli_fetch_assoc($result))
{
comment_id = $row['comment_id'];
echo "<script>";
echo "var count = ".json_encode($comment_id);
echo "</script>";
}
But what I get a last value on while loop is assigned to js variable count as php is server sided and js is client sided. Then I tried adding array (as it can hold many values)
while($row = mysqli_fetch_assoc($result))
{
$comment_id = $row['comment_id'];
echo "<script>";
echo "var count = [];";
echo. "count.push($com);";
echo "</script>";
}
But again i am getting last value in while loop. Is there any way I can assign whole data inside a php while loop to js variable.
Thanks :)
I just got an idea and I think it is now resolved. I did is taken a php array inside while loop and assigned it to js array.
$count = [];
while($row = mysqli_fetch_assoc)
$comment_id = $row['comment_id'];
array_push($count,$comment_id);
echo "<script>";
echo "var count =".json_encode($count);
echo "</script>";
}
I am developing a narrowcasting system for my school and I am currently using a JavaScript to rotate between URL's for the iFrame on the main display page.
I want to be able to change these values through a backend with PHP. However I can't figure out how to put 2 rows (module_url and module_time) into a array and echo it to JS.
Browsing through stackoverflow I tried a variety of code and this one kinda works, except it will throw out URL's like: "var arrayObjects = ["https:\/\/domain.eu\/dir\/page.php","https:\/\/domain.eu\/dir\/page.php"]".
(I want the array to display: "var arrayObjects = ["https:\/\/domain.eu\/dir\/page.php", 20]". Where the URL stands for the new iFrame source and the 20 for the time the page will be displayed.)
So my main question is, how do I make 2 rows fit into 1 array and how do I make sure the array will display correct links aswell as the module time.
<?php
$mysqli = new mysqli('localhost', 'user', 'pw', 'db');
if ($stmt = $mysqli->prepare("SELECT module_url FROM db")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
//put all of the resulting names into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);
?>
<script>
//now put it into the javascript
var arrayObjects = <?php echo $json_array; ?>
ALL OTHER JS CODE
</script>
Edit: module_time is not added to the MySQLi query at the moment.
First your PHP array should be multi-deminsional like:
$result_array[] = array($name, <time here>);
Then since you already use json_encode and assigned it to JS array, it is indeed already an array in Javascript, that is you can already access the elements like:
arrayObjects[0][0]; <---- first element URL
arrayObjects[0][1]; <---- first element time
Printing JavaScript array to HTML will show it as text like:
http://www.google.com,20,http://www.google.com,30
By the way you can use JSON.stringify() to print the actual Javascript array instead of the text, sample:
var array = JSON.stringify(<?php echo $json_array; ?>);
document.write(array);
Will output:
[["http://www.google.com",20],["http://www.google.com",30]]
I am trying to import three arrays from php into js using json_encode
Here is the code:
<?php
$query2 = "SELECT * FROM all_data";
$result2 = $conn->query($query2);
$bu = [];
$rank = [];
$id = [];
if ($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()) {
$bu[] = $row2["bu"];
$rank[] = $row2["rank"];
$id[] = $row2["id"];
echo "<tr class='dn' id='u-" . $row2["rank"] . "'>";
echo "<td>" . $row2["rank"] . "</td>";
echo "<td>" . $row2["bu"] . "</td>";
echo "<td>" . $row2["tokens"] . "</td>";
echo "</tr>";
}
}
?>
var users = <?php echo json_encode($bu); ?>;
var ranks = <?php echo json_encode($rank); ?>;
var identifier = <?php echo json_encode($id); ?>;
Problem is, the arrays ranks and identifier are getting imported correctly, but users is not. This script was working the last few times I used it. Recently however, I changed the table all_data, by dropping it and then importing it from csv again. However the charset was utf8 when I imported, so I don't understand what the problem might be here.
Even if I am just doing <?php echo json_encode($bu) ?> it is not working. However <?php print_r($bu) ?> shows me that the array is not actually empty and it actually contains the query results.
json_encode turns the array into a string; if you want to have access to the array again in Javascript, parse the string back to an array again, such as:
var users = JSON.parse('<?php echo json_encode($bu); ?>');
But it's quite bad practice to create JS on the fly like this - if you want the script to have information served from your PHP, either insert the object into a element which gets parsed by the Javascript, or use data- attributes.
As #kip points out in the comments, the most likely cause of the failure is the conversion of a unicode character, or other special characters that is causing the json_encode to fail to encode the array.
Most likely, you will need to use one of the json_encode predefined constants such as #kip recommended:
json_encode($bu, JSON_UNESCAPED_UNICODE);
I would actually take this a step further and use:
json_encode($bu, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR)
Finally, since you know you are getting a json_encode error of some kind, after running your line
var users = < ? php echo json_encode($bu); ?>;
You can add the line:
json_last_error()
This will tell you exactly what the problem is, and should allow you to adjust the parameters of the json_encode to work with your $bu array.
I have the following PHP code. It creates multiple variables using $a; for example: $numtoken1.
$sql ="SELECT token, dispositivo FROM dispositivos WHERE idcliente=1";
mysql_select_db('localiza');
$retval = mysql_query( $sql, $conn );
$num_rows = mysql_num_rows($retval);
while($row = mysql_fetch_array($retval, MYSQL_BOTH))
{
$numtoken['$a']=$row['token'];
$numdispositivo['$a']=$row['dispositivo'];
$a=$a++;
}
Using JavaScript, I want to call all the PHP variables using that code, but it only get the last $a number.
My question is: In a JavaScript loop, how can I dynamically insert the value for $a? Because in the above PHP, I have multiple values for $a.
var accessToken = "<?= $numtoken['$a']; ?>"a;
var deviceID = "<?= $numdispositivo['$a']; ?>";
I suggest JSON:
var accesstoken = JSON.parse("<?= json_encode($numtoken); ?>");
var deviceID = JSON.parse("<?= json_encode($numdispositivo); ?>");
So the first thing I noticed when looking at this is that you are wrapping $a in single quotes (') instead of double quotes (") this means that instead of evaluating $a the key in the array will be the string "$a", so you'll be overwriting the value in each iteration of the while loop. See - http://php.net/manual/en/language.types.string.php#language.types.string.parsing for more info.
That being said the actual answer to your question varies, but the simplest method might be to use the json_encode function to convert your arrays into json objects.
var accessTokenArr = <?php print json_encode($numtoken); ?>
var deviceIdArr = <?php print json_encode($numdispositivo); ?>
Then you can iterate over the values in those arrays and do whatever you want to with the values. Fair warning - you may need to tweak that code a little as I haven't tested it to make sure it plays nicely.
so I have this code:
var loc = new Array();
<?php foreach($loc as $key => $val) { ?>
loc.push('<?php print_r($val); ?>');
<?php } ?>
The problem is is that it's only showing one value and not more than one, like it should. This is the php array code:
$loc = array($lat, $long);
Any help is greatly appreciated.
Try this:
var loc = <?php echo json_encode($loc); ?>;
You should not use print_r. Let me quote the documentation:
print_r — Prints human-readable information about a variable
Note the part I emphasised. "human-readable". Just because it looks vaguely like something JavaScript might understand, doesn't mean it is ;) json_encode, on the other hand, is specifically designed to output JSON, which is a subset of the syntax JavaScript accepts for variables.