Convert PHP array to JS array (ISO 8859-1 characters) - javascript

I can't get it to work despite all the sources. I try the following :
<?php
$list_array = array();
foreach ($this->resultatTypeMail as $mailType) {
$nom = $mailType->getNom();
$objet = $mailType->getObjet();
$list_array[] = array(
'Name' => $nom,
'Object' => $objet,
);
echo "<script type='text/javascript'>alert('$nom');</script>"; // this is OK
echo "<script type='text/javascript'>alert('$objet');</script>"; // this is OK
}
?>
<script type="text/javascript">
var js_array = [<?php echo json_encode( $list_array ); ?>];
alert(js_array[0]); // This returns undefined
</script>
I get satisfying results on $nom and $objet when I alert them.
Problem :
js_array[0] returns undefined
Note that I'm not in UTF-8. I'm not sure it's relevant though.
EDIT : A big picture of my goal is to get an array of custom php objet to be usable in JS.

Just remove the [] from var js_array = line and it will work:
wrong:
var js_array = [<?php echo json_encode( array_values($list_array) ); ?>];
right:
var js_array = <?php echo json_encode( array_values($list_array) ); ?>;
Working code:
<?php
class MailType {
function __construct($n, $o) {
$this->nom = $n;
$this->objet = $o;
}
private $nom;
private $objet;
public function getNom() {
return $this->nom;
}
public function getObjet() {
return $this->objet;
}
}
$list_array = array();
$resultatTypeMail = array(new MailType('John', 'obj1'), new MailType('Mary', 'obj2'));
foreach ($resultatTypeMail as $mailType) {
$nom = $mailType->getNom();
$objet = $mailType->getObjet();
$list_array[] = array(
'Name' => $nom,
'Object' => $objet,
);
//echo "<script type='text/javascript'>alert('$nom');</script>"; // this is OK
//echo "<script type='text/javascript'>alert('$objet');</script>"; // this is OK
}
?>
<script type="text/javascript">
var js_array = <?php echo json_encode( $list_array ) ?>;
alert(js_array[0].Name); // This returns John
</script>
You can see it running here: http://phpfiddle.org/main/code/5xei-ybpn
(press F9 or click on 'Run - F9' to Run)

In PHP an array that has string keys gets converted to an object when parsed with json_encode.
You could either use array_keys to force the creation of an array, or use the object notation in your javascript
<?php
$list_array = array();
foreach ($this->resultatTypeMail as $mailType) {
$nom = $mailType->getNom();
$objet = $mailType->getObjet();
$list_array[] = array(
'Name' => $nom,
'Object' => $objet,
);
echo "<script type='text/javascript'>alert('$nom');</script>"; // this is OK
echo "<script type='text/javascript'>alert('$objet');</script>"; // this is OK
}
<script type="text/javascript">
var js_array = [<?php echo json_encode( array_values($list_array) ); ?>];
alert(js_array[0]);
</script>
Or
<?php
$list_array = array();
foreach ($this->resultatTypeMail as $mailType) {
$nom = $mailType->getNom();
$objet = $mailType->getObjet();
$list_array[] = array(
'Name' => $nom,
'Object' => $objet,
);
echo "<script type='text/javascript'>alert('$nom');</script>"; // this is OK
echo "<script type='text/javascript'>alert('$objet');</script>"; // this is OK
}
<script type="text/javascript">
var js_array = [<?php echo json_encode( array_values($list_array) ); ?>];
alert(js_array.Name);
</script>

I think you have multiple issues: you're missing the ; after the json_encode() line (which is not actually required); you're surrounding the result of json_encode() with brackets (which should work but I expect it's not what you want); and the most important, you're missing the closing PHP ?> tag before printing the JS...
This works for me:
<?php
// your PHP code here...
?>
<script type="text/javascript">
var js_array = <?php echo json_encode($list_array); ?>;
alert(js_array[0]); // This works for me!
</script>
It looks like the issue may be in the encoding as you say - it seems that json_encode only works with UTF-8! From the json_encode() docs:
All string data must be UTF-8 encoded.
So I think you'll have to convert your strings to UTF-8 before putting them into the array, something like:
$list_array[] = array(
'Name' => utf8_encode($nom),
'Object' => utf8_encode($objet),
);
I think just that should work - otherwise you can try this from the comments in the same json_encode() docs; or this other question to get more ideas...

Related

Converting PHP array to JS array in PHP itself

Hey just a small thing I am stuck on.
I do have the structure ready for the JS array but I need to assign it to a variable like
var data ={ Php array }
Here is the structure of my php array: https://imgur.com/a/LPbCqEu This is just a part of the array.
My code looks like this:
$csvfile = 'Property_CSVTruncated.csv';
$handle = fopen($csvfile, 'r');
$jsData = array(
'properties' =>array()
);
$header = NULL;
while (($row = fgetcsv($handle, 1000000, ',')) !== FALSE) {
$i = 0;
if (!$header) {
$header = $row;
} else {
$data = array_combine($header, $row);
$fields = array(
'_id' => $data['C4021040'],
'index' => $i,
'price' => $data['123'],
'picture' => "https://ihatetomatoes.net/demos/_rw/01-real-estate/tn_property01.jpg",
'city' => "Calgary",
'MLS# ' => $data['C4021040'],
'address' => $data['6 ASPEN RIDGE LN SW'],
'latitude' => $data['51.045681'],
'longitude' => $data['-114.191544'],
'Bed' => $data['123'],
'Bath' => $data['123'],
'capSpaces' => $data['T3H 5H9'],
);
array_push($jsData['properties'], $fields);
}
$i++;
}
fclose($handle);
$str = "const data = ";
print($str);
header('Content-type: application/json');
json_encode($jsData, JSON_NUMERIC_CHECK);
$jsonFile = fopen('csvTojs.js', 'w');
fwrite($jsonFile, json_encode($jsData));
fclose($jsonFile);
So basically I need that string 'var data = ' and then prints the array.
Anyway to do that in php itself?
Thanks
in server, echo json_encode($phpArray) and exit;
in callback of ajax or init js variable, parse json to array with JSON.parse('jsonString');
Use json_encode()
<script>
var data = <?php echo json_encode($jsData, JSON_PRETTY_PRINT); ?>
</script>
Or in your case:
header('Content-Type: application/json');
echo json_encode($jsData);
exit;

for loop to set javascript variable = to a php variable

I am working on a project that requires create hundreds of variables in javascript with PHP values. I can write each one line by line like so:
var M1 = <?php echo json_encode($$mn[0]); ?>;
var M2 = <?php echo json_encode($$mn[1]); ?>;
var M3 = <?php echo json_encode($$mn[2]); ?>;
As I said there are hundreds of these though and if it is possible to do in a loop I would be very interested in learning. I have searched all over and can't find a direct answer. It may very well be that this is not possible. I am new to coding and still learning what certain code can and cannot do.
Any insight or direction on this topic would be greatly appreciated!
If this is not an option is it possible to use an array index for the javascript variable name? I have created an array for the JS and PHP. The PHP works fine above but if I try to use an array index for the JS like below, it breaks:
var mcirc[0] = <?php echo json_encode($$mn[0]); ?>;
I have output the array and the values are coming up correctly but when I run this I get the message:
[object HTMLDivElement]
instead of the actually value that should show up.
UPDATE
$mn array:
for ($m1 = 1; $m1 < 6; $m1++) {
$mn[] = 'M'.$m1;
}
UPDATE
Select SQL creating array:
$sqlMC = "SELECT * FROM tblmaincircles";
$result = $conn->query($sqlMC);
while($row = $result->fetch_assoc()) {
$$row["mcID"]= $row["mcName"];
}
The array for mcID looks like this:
M1 = "text1"
M2 = "text2"
M3 = "text3"
M4 = "text4"
M5 = "text5"
UPDATE
end result desired:
var M1 = "text1";
var M2 = "text2";
var M3 = "text3";
var M4 = "text4";
var M5 = "text5";
Where "text1, ...2, ...3, ...4, ...5" are coming from the MySQL database.
UPDATE
Here is the final code that got this working:
$sqlMC = "SELECT mcID, mcName FROM tblmaincircles";
$result = $conn->query($sqlMC);
while($row = $result->fetch_assoc()) {
$mcID[] = $row["mcID"];
$mcName[] = $row["mcName"];
}
<?php for ($m1 = 0; $m1 <5; $m1++) { ?>
var <?php echo $mcID[$m1]; ?> = <?php echo json_encode($mcName[$m1]); ?>;
<?php } ?>
Simply put JSON into variable
var json = <?php echo json_encode($$mn); ?>;
And then process the JSON way you want:
eg.
var json=[{key:someValue},
{key:someValue2},
{key:someValue3}
];
json.forEach(function(a){
console.log(a.key);
})
First in your query part, declare a variable to hold the result that you want. I'm assuming the M1 is mcID in your table and text1 is the mcName. For example:
$sqlMC = "SELECT * FROM tblmaincircles";
$result = $conn->query($sqlMC);
$mac = [];//or $mac = array(); Depends on your PHP version.
while($row = $result->fetch_assoc()) {
$mac[$row["mcID"]] = $row["mcName"];
}
And then, iterate through the $mac array with foreach loop. I'm assuming you are using PHP codes within HTML. The $key will be the mcID and the $value will be the mcName.
//php tag for the foreach opening
<?php foreach ($mac as $key => $value) { ?>
var <?php echo $key; ?> = <?php echo "'$value';"; ?>
//php tag for the foreach closing
<?php } ?>
OR, if you want to use javascript associative array.
var macJs = {};
<?php foreach ($mac as $key => $value) { ?>
macJs.<?php echo $key; ?> = <?php echo "'$value';"; ?>
<?php } ?>
And you can access the element like this in javascript macJs.M1.
You should use JSON to 'export' your objects/array through different languages, in that case:
var json = '<?= json_encode($your_array); ?>';
After this you can parse this Json, what should return your array:
var your_array = JSON.parse(json);

Get JSON format from MySql to javascript using PHP

i want to get the json format from my SQL database using PHP
here is a capture of mySql database
data.php
<?php include("include/connexion.php");
$requete = "SELECT * from statistika";
$resultat = mysql_query( $requete ) or die( mysql_error() );
$rows = array();
$total_vue = 0;
here is the php code to get the data
while( $data = mysql_fetch_assoc( $resultat ) ) {
$total_vue+=$data['temps'];
$rows[] = array(
"date" => strtotime( $data['date']) * 1000,
"value" => $data[ 'temps' ]
);
}
?>
json_encode.php
<?php
include("data.php");
echo json_encode($rows);
?>
The content of json_encode is valid and i get the json format successfully
[{"date":1439769600000,"value":"5"},{"date":1439787600000,"value":"12"},{"date":1439806631000,"value":"8"},{"date":1439821320000,"value":"18"},{"date":1439919642000,"value":"6"},{"date":1439889752000,"value":"2"},{"date":1439893260000,"value":"20"},{"date":1439906400000,"value":"9"},{"date":1429308000000,"value":"15"},{"date":1421535600000,"value":"12"},{"date":1413583200000,"value":"18"},{"date":1405634400000,"value":"6"},{"date":1439828640000,"value":"14"},{"date":1439935200000,"value":"19"},{"date":1439863200000,"value":"12"},{"date":1439884800000,"value":"18"},{"date":1439917200000,"value":"26"},{"date":1439920800000,"value":"4"},{"date":1439904320000,"value":"0"},{"date":1439907420000,"value":"1"},{"date":1439907428000,"value":"1"},{"date":1439907434000,"value":"3"},{"date":1439907437000,"value":"1"},{"date":1439907447000,"value":"8"},{"date":1439907452000,"value":"3"},{"date":1439907459000,"value":"5"},{"date":1439907469000,"value":"8"},{"date":1439907482000,"value":"10"},{"date":1439907507000,"value":"21"},{"date":1439907510000,"value":"1"},{"date":1439907519000,"value":"7"},{"date":1439907526000,"value":"5"},{"date":1439907547000,"value":"18"},{"date":1439907557000,"value":"8"},{"date":1439907560000,"value":"1"},{"date":1439907576000,"value":"3"},{"date":1439907581000,"value":"3"},{"date":1418857200000,"value":"300"},{"date":1426633200000,"value":"450"},{"date":1434578400000,"value":"500"},{"date":1424214000000,"value":"600"}]
Now i want to pass the JSON format to javascript , i am using this code
var foo = {};
foo.toString = function () { return <?php echo json_encode($rows);?> };
document.write(foo.toString);
the problem is that when printing foo.toString i get this
function () { return [{"date":1439769600000,"value":"5"},{"date":1439787600000,"value":"12"},{"date":1439806631000,"value":"8"},{"date":1439821320000,"value":"18"},{"date":1439919642000,"value":"6"},{"date":1439889752000,"value":"2"},{"date":1439893260000,"value":"20"},{"date":1439906400000,"value":"9"},{"date":1429308000000,"value":"15"},{"date":1421535600000,"value":"12"},{"date":1413583200000,"value":"18"},{"date":1405634400000,"value":"6"},{"date":1439828640000,"value":"14"},{"date":1439935200000,"value":"19"},{"date":1439863200000,"value":"12"},{"date":1439884800000,"value":"18"},{"date":1439917200000,"value":"26"},{"date":1439920800000,"value":"4"},{"date":1439904320000,"value":"0"},{"date":1439907420000,"value":"1"},{"date":1439907428000,"value":"1"},{"date":1439907434000,"value":"3"},{"date":1439907437000,"value":"1"},{"date":1439907447000,"value":"8"},{"date":1439907452000,"value":"3"},{"date":1439907459000,"value":"5"},{"date":1439907469000,"value":"8"},{"date":1439907482000,"value":"10"},{"date":1439907507000,"value":"21"},{"date":1439907510000,"value":"1"},{"date":1439907519000,"value":"7"},{"date":1439907526000,"value":"5"},{"date":1439907547000,"value":"18"},{"date":1439907557000,"value":"8"},{"date":1439907560000,"value":"1"},{"date":1439907576000,"value":"3"},{"date":1439907581000,"value":"3"},{"date":1418857200000,"value":"300"},{"date":1426633200000,"value":"450"},{"date":1434578400000,"value":"500"},{"date":1424214000000,"value":"600"}]
i don't want function () { return to appear in the output !!!
Any hints ?
thanks .
Change this line in your JS code
From
foo.toString = function () { return <?php echo json_encode($rows);?> };
To
foo.toString = '<?php echo json_encode($rows);?>';
var foo = {};
foo.toString = function () { return <?php echo json_encode($rows);?> };
document.write(foo());
You are creating foo as function so call like this you will get only json.

csv to JSON not working

I have a csv file that I want transfer into JSON but it doesn't work the way I was hoping
PHP
$file = $_FILES['csv']['tmp_name'];
$csv= file_get_contents($file);
$array = array_map('str_getcsv', explode(";", $csv));
echo "<script type='text/javascript'>alert('OK!');</script>";
javascript
var myJsarray = <?= json_encode($array); ?>;
alert(myJsarray[0][0]);
my csv looks something like this
aaa;46
bbb;23
ccc;51
ddd;23
and my output looks like this
[["aaa"],["46\r\nbbb"],["23\r\nccc"],["51\r\nddd"],["23"]];
and I was hoping to get
[["aaa"],["46"],["bbb"],["23"],["ccc"],["51"],["ddd"],["23"]]
my idea was to put "$csv=explode("\n", $csv)" under "$csv= file_get_contents($file); "
But it gave me error that "$csv is not a string.
http://jdl-enterprises.co.uk/sof/25763045.php
If it's something like this that you want:
$csv= file_get_contents($file);
$array = explode("\r\n", $csv); // Update this to \n if need be or however you csv saves it
for($i=0;$i<count($array);$i++){
$array[$i] = explode(';', $array[$i]);
}
This will produce:
[["aaa","46"],["bbb","23"],["ccc","51"],["ddd","23"]]
And if you want it like your example, add into the code:
$array2 = array();
foreach($array as $ar) {
foreach($ar as $a) {
$array2[] = $a;
}
}
This will produce:
["aaa"],["46"],["bbb"],["23"],["ccc"],["51"],["ddd"],["23"]
Obviously there is a set of [ ] missing around the whole code, but you could stuff it all inside another array, or just add them manually.
Your "CSV" is in an incorrect format:
aaa;46 bbb;23 ccc;51 ddd;23
Change it to:
aaa,46 bbb,23 ccc,51 ddd,23
You do know there is a function just for reading CSV in PHP? It's called fgetcsv()
$data = array();
$fh = fopen('file.csv', 'r');
while (($line = fgetcsv($fh, 0, ';')) !== false) {
$data[] = $line;
}
fclose($fh);
echo json_encode($data);

to combine Javascript HTML PHP

I am doing this little project. Everything seems working , but I want to make even better.
I have code
-Part1 -takes date from database and converts to JSON
<?php
$sth = mysql_query("select Value, Stats from table");
$rows = array();
$flag = true;
$table = array();
$table['cols'] = array(
array('label' => 'Stats', 'type' => 'string'),
array('label' => 'Value', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
$temp[] = array('v' => (string) $r['Stats']);
$temp[] = array('v' => (int) $r['Value']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table, JSON_NUMERIC_CHECK);
?>
-Part 2 Draws Google Bar chart and shows it on page
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
var options = {
legend: {position: 'none'},
bar: {groupWidth: "85%"},
colors:['#4A9218'],
hAxis: {viewWindowMode: 'explicit'},
} };
var chart = new google.visualization.BarChart(document.getElementById('charts_div'));
chart.draw(data, options);
}
</script>
<div class='data' id="charts_div" style="width:100%; height:200px"></div>
-My Qyestion
How to convert (combine) Part2 code to php. I tried echo around lines, but unsuccesfully
I want to assign Part2 as Php variable $Graph1 and then echo $graph1 on page, because It works better with my other code, so its consistent.
So I would like something like:
<?php
Part1
?>
<?php
$graph1=."<script>...</script>"
$graph = "<div class='data'><ul>" . $graph1 . "</ul></div>
echo $graph
?>
Why don't you just add it after the ?> ?
In PHP you can include HTML like this
<?php
// My PHP Code
echo "test";
?>
<H1>My Title in HTML</H1>
<script> ... </script>
<?php
echo "test2";
?>
You can also include PHP into HTML
<script> var a = "<?php echo $somevariable; ?>"</script>
You can also wrap your HTML code into a PHP variable care about the ". You will need to escape it or us single quote instead:
<?php
$myHTML = "<script> window.location=\"mylocation.com\";</script>";
$myHTML = "<script> window.location= 'mylocation.com' ;</script>";
...
echo $myHTML;
?>

Categories