PHP to Javascript array trouble - javascript

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.

Related

Calling JSON.parse on php returned array, some numbers parsed as INT, others parsed as STRING

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.

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.

2 php arrays into one 2d javascript array

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

Add a comma to the end of each line using php [duplicate]

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.

Categories