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.
Related
Looking for an explanation rather than an answer here :)
I have this php script that is called with jquery's AJAX
$query = 'SELECT MONTH(PRSD#) as "Monat", CAST(AVG(GASVBR) as DECIMAL(10,3)) as "Gas", CAST(AVG(OLVBR) as DECIMAL(10, 3)) as "Öl", CAST(AVG(STROVBR) as DECIMAL(10,3)) as "Strom" FROM swind.gwenergy GROUP BY YEAR(PRSD#), MONTH(PRSD#) ORDER BY MONTH(PRSD#)';
$dbReturn = $database->execute($query, array());
$jsonArray = array();
while ($row = db2_fetch_assoc($dbReturn)) {´
echo json_encode($jsonArray);
}
When I call in the JS side of things:
let parsedData = JSON.parse(jsonData);
I am returned with this:
{Monat: 2, Gas: '13750.607', Öl: '1447.432', Strom: '3901.051'}
How come the Monat value is not in quotes?
I thought that maybe because the $query in the php script was returning DECIMAL(10,3) but when I replace it with FLOOR(... the JSON.parse still wrapped the value in quotes. Is this related to the $query response, or is this a JSON.parse action?
Look forward to hearing other ideas :) Thanks! -Boogabooga
I've faced a similar problem.
You can check the data type on PHP with gettype()
Note that since PHP 5.3.3, there is a flag for auto-convert numerical numbers when using json_encode.
echo json_encode( $jsonArray, JSON_NUMERIC_CHECK );
This should do the work for you.
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 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 have this array:
$men['display']=array(
"edit" =>"1",
"description" =>"2",
"phone" =>"3",
"mail" =>"4"
);
I tried to transfer it to javascript by using:
<?php $disArray = json_encode($men['display']);?>
then, I sent it to javascript:
<select id="selectBoxHere" onChange="loadInnerHTML('<?php $disArray ?>')";>
For some reason, my javascript function 'loadInnerHTML' dosen't send my array to javascript.
You forget the echo statment.
And if you use single quotes, it makes this a string. For a javascript object you don't need the single quotes, json_encode will ensure it is javascript safe.
loadInnerHTML(<?php echo $disArray ?>)
I'd also recommend that you store this variable directly in javascript first, rather than passing it into a function. Otherwise you have to worry about double quotes inside double quotes, breaking your <select> tag.
var disArray = <?php echo $disArray ?>;
Then you can just use that variable.
loadInnerHTML(disArray)
Echoing an array in php will result in
var dis_array = Array
which js couldn't understand. Try:
var disArray = JSON.parse( '<?php echo json_encode( $disArray ) ?>' );
This question already has answers here:
Convert php array to Javascript
(21 answers)
Closed 9 months ago.
I am having a csv file with 1 email id in each line. I want to add comma after each email id. I want to add a comma to the end of each line using php. How can i do this? Is there a particular function for that?
UPDATE
I want this so that I can construct an array out of it in javascript.
I will be loading the csv file using php and then printing it in my js.
Like
var myCars=[<?php print $csv; ?>];
So that I acheive something like this.
var myCars=["Saab#gmail.com","Volvo#gmail.com","BMW#gmail.com"];
Or is there a better way to do this?
$lines = file('file.csv');
foreach ( $lines as & $line ) {
$line .= ',';
}
file_put_contents('file.new.csv', implode(PHP_EOL, $lines));
something like that should do,
cheers
<?php
$lines = file('org.csv');
foreach ( $lines as & $line ) {
$line = trim( $line ) . ',';
}
file_put_contents('new.csv', implode(PHP_EOL, $lines));
Why not use the csv-specific functions?
$old = fopen('file.csv','r');
$new = fopen('new.csv','w+');
while($line = fgetcsv($old))
{
fputcsv($new,$line);
}
fclose($old);
fclose($new);
The above code will write a new csv, line per line, but if you just want to generate a javascript array, why not do this:
$file = fopen ('file.csv','r');
$all = array();
while($line = fgetcsv($file))
{
$all[] = $line[0];//if there is only 1 field/line
$all = array_merge($all,$line);//if multiple
}
fclose($file);
$js_array = '["'.implode('",',$all).'"];';
//or, the way I'd advise against, but good for multi-dimensional, assoc arrays
echo 'var array = JSON.parse("'.json_encode($all).'");';
why not just
$csv = str_replace("\n", ",\n", $csv);
Instead of echoing an entire csv string, you can import the file to an array using the fgetcsv function, then echo it out using json_encode(). That way you're sure to get a valid javascript array. It will also quote and encode any strings for you.
Oh, remember to run the array through some iterator which will run utf8_encode on all strings. If you have invalid utf8 characters, json_encode will barf.
There are plenty of examples on php.net of doing the different parts of this, but I can provide some examples if needed.