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;
?>
Related
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;
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...
How to create var javascript via php ?
<?PHP
include("connect.php");
$get_data = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
while($resilt_row = mysqli_fetch_array($get_data))
{
$bad_words = $bad_words."".$resilt_row [word].",";
}
//echo $bad_words;
?>
<script>
var bad_words = ["<?PHP echo $bad_words; ?>"];
alert(bad_words);
</script>
I want to get var javascript like this var bad_words = ["fuck", "ass"];
When alert it's get only blank result.
How can i do that ?
<?php
include("connect.php");
$query = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
$badWords = [];
while($row = mysqli_fetch_array($query))
{
$badWords[] = $row['word'];
}
js
<script>
var bad_words = <?= json_encode($badWords); ?>;
alert(bad_words[0]);
console.log(bad_words);
</script>
I don't like gluing the strings if it's an array then pass it as an array with json_encode() function. Also in views it's better to use short syntax with <?= ?> tag
The string you're making is not the one you want.
You're not adding quotes.
Do this instead, using an array is better:
$get_data = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
$bad_words = array();
while($resilt_row = mysqli_fetch_array($get_data))
{
$bad_words[] = "'" . $resilt_row[word]. "'";
}
And then, down in your js:
var bad_words = ["<?php echo implode(",", $bad_words) ?>"];
or (for short)
var bad_words = ["<?= implode(",", $bad_words) ?>"];
If you want alert them as a string you can do it like this:
<script>
var bad_words = ["<?php echo implode('","',$bad_words); ?>"];
alert(bad_words);
</script>
Otherwise, you can print them as an array:
<script>
var bad_words = <?php echo json_encode($bad_words) ?>;
console.log(bad_words);
</script>
<?PHP
include("connect.php");
$get_data = mysqli_query($db_mysqli,"SELECT * FROM bad_word");
while($resilt_row = mysqli_fetch_array($get_data))
{
$bad_words[] = $resilt_row['word'];
}
//echo $bad_words;
?>
<script>
var bad_words = ["<?php print implode('","',$bad_words); ?>"];
alert(bad_words);
</script>
I have an array $results and I need to use it inside my javascript part of the code. I tried json_encode() but it did not work..
Here is the code
<?php
//...
include realpath($_SERVER['DOCUMENT_ROOT'] . '/Classes/Controllers/ReportController.php');
$vaccRep= ReportController::getVacRep();
include realpath($_SERVER['DOCUMENT_ROOT'] . '/Classes/Controllers/VaccineController.php');
$names=VaccineController::getVCName();
?>
<canvas id="bar" height="195" width="250" style="width: 250px; height: 195px;"></canvas>
<script>
//THIS IS THE PART THAT WILL BE THE OTPUT OF THE QUERY
var barChartData = {
labels: <?php$obj=json_encode($names); var_dump($obj);?>,
datasets: [{
highlightFill: "#45668e",
highlightStroke: "#45668e",
fillColor : "#1ABC9C",
strokeColor : "#1ABC9C",
data: <?php $obj=json_encode($vaccRep); var_dump($obj);?>
}]
};
new Chart(document.getElementById("bar").getContext("2d")).Bar(barChartData);
<?php $obj=json_encode($vaccRep); var_dump($obj);?>
</script>
Simply echo the php array in js with json_encode(), like this :
$phpArray = array('name'=>'mani','email'=>'test#gmail.com','mobile'=>'123467890');
PHP array looks like this
Array
(
[name] => mani
[email] => test#gmail.com
[mobile] => 123467890
)
<script>
var jsArray = [];
var jsArray = <?php echo json_encode($phpArray);?>;
console.log(jsArray);
</script>
You will get this in your console
Object { name="mani", email="test#gmail.com", mobile="123467890"}
how about
<?php
echo "<script>";
echo "var $results = JSON.parse('" . json_encode($results) . "');";
echo "<script>";
?>
and then use $results in your javascript code anywhere but make sure this script block is loaded before you are using it.
You can try like this to print a php array in javascript
<?php
$abc=["a","b","c"];
?>
<script type="text/javascript">
var abc = "<?php echo (implode(',',$abc));?>";
var abcArr = abc.split(",");
console.log(abcArr);
</script>
You can simply use this code:
<?php
$array = ["a", 1, 2, "b,"];
echo "<script>";
echo "var data = ".json_encode($array).';';
echo "</script>";
?>
The output of this code will be:
<script>var data = ["a",1,2,"b,"];</script>, what will create correct javascript array.
I have the following in my page header
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="javascript/autoSuggest.js"></script>
<script type="text/javascript" src="javascript/suggest.js"></script>
suggest.js is made of:
$(function(){
$("#idName input").autoSuggest("../Test.php", {minChars: 2, matchCase: true});
});
and autoSuggest.js is a plugin by Drew Wilson (http://code.drewwilson.com/entry/autosuggest-jquery-plugin)
Test.php is
<?php
include('database_info.inc');
$input = $_POST["idName"];
$data = array();
var_dump($data);
// query database to see which entries match the input
$query = mysql_query("SELECT * FROM test WHERE title LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['title'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>
My var_dump() doesn't do anything and no items are suggested ...what could I be doing wrong? seems like there's no communication with Test.php
A quick look at the plug-in suggests it expects a parameter called q passed as a GET string, not as a POST.
<?
$input = $_GET["q"];
$data = array();
// query your DataBase here looking for a match to $input
$query = mysql_query("SELECT * FROM my_table WHERE my_field LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['username'];
$json['image'] = $row['user_photo'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>