2 php arrays into one 2d javascript array - javascript

I have this code:
$lat = $obj['geo']['coordinates'][0];
$long = $obj['geo']['coordinates'][1];
Its to do with google maps. So these two variables take the coordinate values (lat and long) from a mongodb. Assume this works.
And I have this in the javascript:
var loc = <?php echo json_encode($lat, $long); ?>;
I'm attempting here to make these two php arrays into a 2d javascript array, but it's not working.
Any help is greatly appreciated!

Try this:
var loc = <?php echo json_encode(array($lat, $long)); ?>;
If it's not that what you need, just tell it, i have some more ideas ;-)

Related

How do I convert a php date_diff value to a javascript integer?

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).

Putting two MySQL rows into an PHP array

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]]

Pass PHP array values to JavaScript variable

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']}); ?>";

JavaScript - Bring multiple variables from PHP

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.

PHP to Javascript array trouble

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.

Categories