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]]
Related
I'm trying to use the difference between two dates to help me draw lines on an HTML canvas. I generate one date in PHP and extract the other which is stored in an SQL database
When I keep everything in PHP the echo'd output is exactly what I expect. However, when I json_encode the output, which I expect to be an integer, to use to draw the shape I want on the canvas, a completely different number is presented from javascript.
I'm pretty sure it has to do with the json encoding ... but I haven't been able to find any reference about how to do this properly.
Here's the PHP I use to grab, format, and create a date difference output:
$sdt = new DateTime($row['sdate']);
$today = new DateTime('now');
$sdiff = date_diff($sdt, $today);
$sdelta = $sdiff->format("%a");
If I keep all of this in PHP and either echo the variable or echo the json_encode variable I get the expected answer, which is 34.
echo $sdelta;
results in 34
echo json_encode($sdelta);
results in "34";
echo json_decode($sdelta);
results in 34;
However when I assign this value to a javascript variable and test the result of the assignment:
var diffdt = <?php echo json_encode($sdelta); ?>;
alert(diffdt);
The alert popup shows 199.
If anybody could help me with this issue, I'd be eternally grateful.
Extra information...
Column type for sdate is DATE
query I'm executing is to get the data is:
$stmt = $link->prepare("SELECT * FROM register WHERE id = ? ");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$num = $result->num_rows;
$row = $result->fetch_assoc();
var_dump($row['sdate']);
Number of rows is 1.
vardump result is: string(10) "2019-09-27"
Must use "Number(your_number)" method I used here,see bottom line:
<script type="text/javascript">
// To set two dates to two variables
var date1 = new Date("06/30/2019");
var date2 = new Date("07/30/2019");
// To calculate the time difference of two dates
var Difference_In_Time = date2.getTime() - date1.getTime();
// To calculate the no. of days between two dates
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
console.log(Number(Difference_In_Days));
</script>
Ended up resolving this issue by moving php code outside some of the javascript I had written. Problem was from a for loop I had implemented that updated javascript values from the php loop. This was adding up the result. None of my code actually changed, it was just rearranged.
Didn't think this was an issue since the for loop was doing it's job for what it was designed.
Thanks everyone for your help. It allowed me to eliminate most of the other potential issues.
airider74 When you say that PHP shows the correct data but JS does not, what are you using to display the values-- i.e. console/terminal/browser etc. ? Are they both using UTF8? Something you might try is encoding the output from the PHP via urlencode() and then decode it in JS via decodeURI() .
PHP:
echo urlencode(dIffdt);
JS:
var diffdt = "37"; alert( decodeURI(diffdt) );
Or try base64 encoding.
PHP:
echo base64_encode(diffdt);
JS:
var diffdt = "37"; alert( btoa(diffdt) );
I am thinking possibly your data is ASCII coming out of the server, but JS uses UTF8 by default (as do most modern browsers in a more general sense).
I have a small PHP script I have written that gets reviews from a website. However, I am trying to display them in Javascript but cannot get the values through to the JS.
in PHP I have the variable $reviewTitles populated using:
$reviewTitles = $xpath->query("//*[#class='" . $reviewStr . "']");
and I can access each value in PHP by using
$title = $reviewTitles->item($x)->nodeValue;
Where $x is the index of the title to display.
My question is how can I convert whatever object the php variable $reviewTitles holds into javascript, So I am able to access each title via a JavaScript array.
I have tried:
<script language="JavaScript" type="text/javascript">
var titles = '<?php echo json_encode($reviewTitles); ?>';
var titles_data = JSON.parse(titles );
window.alert(titles_data[0]);
</script>
But get nothing - What am I doing wrong?
Thanks for taking the time to read this.
I have build a dynamic list from an array and must print the onclick event inline, I don't know of anyway other way to do this.
<?php
$dataArray = $_POST['dataArray']; // This is a valid array
ECHO '<div id="colorSelectorBox">';
for ($btn = 0; $btn < sizeof($dataArray); $btn++){
ECHO '<div class="btn-group">
<button onclick="buildGroupList("'.$dataArray.'")">' .$dataArray[$btn].'</button>
<button><div ..Stuff..></div></button>
</div><br>';
}
ECHO '</div>';
?>
The problem is that the JavaScript function buildGroupList() does not receive an array from this instead the line looks like this in my developer tool:
onclick="buildGroupList(Array)"
How can I pass in an array of values through to JavaScript?
OR
How can I re-write this so that the call is not inline?
The shortest answer is: use json_encode() which will convert the array to a json string, but it's not good practice anyway.
Because you are trying to print the array as if automagically transforms itself into javascript array, that is, a string of its values separated by a comma (that is what it needs to output to the html, something the browser understands).
For that you need implode:
string implode ( string $glue , array $pieces )
Join array elements with a $glue string.
ECHO "<div class=\"btn-group\">
<button onclick=\"buildGroupList(['".implode("','",$dataArray)."'])\">" .$dataArray[$btn]."</button>
<button><div ..Stuff..></div></button>
</div><br>";
It takes every element in the array and puts $glue string between every one of them. The end result looks like this:
//let's assume this is your array in PHP
<?php
$dataArray = array('one','two','three');
?>
<!-- then your HTML looks like this -->
<button onclick="buildGroupList(['one','two','three'])">...</button>
Remember that PHP and Javascript don't know each other.
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.
Okay so I know this has been asked before and I've tried the solutions, but for some reason they don't work for me so I'm asking for some help. I haven't used JSON yet so maybe it's something silly but I have no clue...
Here's the code:
<?php
$array;
#successful attempt to display array with json_encode in php
echo json_encode($array);
?>
<html>
<input id="show" type="button" onclick="showArray()" value="showArray">
<divShow>
</divShow>
<script>
function showArray(){
var array = <?php echo json_encode($array); ?>;
//Failed attempt to display array in the div field show
document.getElementById("divShow").appendChild(array);
//Failed attempt to display the array with an alert.
for(var i=0; i<2; i++){
alert(array[i]);
}
};
</script>
</html>
So what do you guys think? Am I missing something? Is it possible that the array was successfully passed to javascript but for some reason won't show?
Thanks,
-Alex
EDIT:
So I'm getting a series of arrays from a text file. I use these arrays as strings to display on the page and then convert them to float arrays. When I echo one of the float arrays such as $Z_Ausmass with:
echo json_encode($Z_Ausmass);
I get [25.39999961853,121.48651123047]. However, when I use the following to display the array through javascript:
function calc(){
var Z_Ausmass = <?php echo json_encode($Z_Ausmass); ?>;
for(var o=0; o<Z_Ausmass.length; o++){
var textnode = document.createTextNode(Z_Ausmass[o]);
document.getElementById("divCalc").appendChild(textnode);
}
};
it does not work. It's vital I get the float arrays in the script because the script needs to make calculations based on them and then display the calculations to the user.
When i execute the code it works ok.
The first attempt fails because you can't append the complete array. You need to append each element in the array seperately.
The second attempt works correctly. You only need to remove the first attempt to make it work because the first attempt stops the execution of the javascript.
edit
I tried to fix the code for you. I used a simple array with only text.
The element you wanted to show in did not have the id you where referencing to
<divShow></divShow>//wrong
<div id="divShow"></div>//right
to loop trough the complete array you do not want to hard code the max # of elements use arr.length as max for the 'for'-loop.
You can't directly append raw text to an html element. You need to make a TextNode of it and then append that node to the html element.
var textnode=document.createTextNode(arr[i]);
document.getElementById("divShow").appendChild(textnode);
So The working code will be something like this:
<?php
$array = array("test","text","show");
#successful attempt to display array with json_encode in php
echo json_encode($array);
?>
<html>
<input id="show" type="button" onclick="showArray()" value="showArray">
<div id="divShow">
</div>
<script>
function showArray(){
var arr = <?php echo json_encode($array); ?>;
//Put the text in a text node, append to the div
for(var i=0; i< arr.length; i++){
var textnode=document.createTextNode(arr[i]);
document.getElementById("divShow").appendChild(textnode);
}
};
</script>
</html>