I’ve a questionnaire that I analyze with php. The data are supposed to be displayed in a Java-based polar-graph and a table.
You can see how it looks with static data here.
However, the graph doesn’t show when I use the data from my database. The table works fine. A few days ago I asked about how to integrate php-data to java via json_encode because I thought this might be the problem, but I learned (thanks again) that this is the correct approach.
My web-hoster says that it doesn’t support php in html, so I modified the index.html to an index.php. I have no idea what to modify to make it work. Database-connection works, php-values in the table are correct, the js-graph works fine with static data.
Here are my php-arrays:
$arr1 = array(axis => "Gesundheitszustand", value => $X1P);
$arr2 = array(axis => "BMI", value => $X3);
$arr3 = array(axis => "Stress", value => $X10P);
$arr4 = array(axis => "Körperliche Aktivität", value => $X4P);
$arr5 = array(axis => "Nahrung: Gemüse/Obst", value => $X8d);
$arr6 = array(axis => "Nahrung: Fisch", value => $X8f);
$arr7 = array(axis => "Nahrung: Fleisch", value => $X8h);
$arr8 = array(axis => "Geistige Gesundheit", value => $X9P);
$arr9 = array(axis => "Zufriedenheit", value => $X2P);
$arr10 = array(axis => "Rauchen", value => $X9a);
The values are numbers between 0 and 1.
That’s how I try to include the js-file in my php-file:
<html>
<head>
<script src="d3js.js"></script>
<script src="radarchart.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php ?>
<script type="text/javascript" src="script.js"></script>
<?php ?>
</body>
And that’s how I include my php-data to the js-file:
var d = [
[
<?php echo json_encode($arr1); ?>,
<?php echo json_encode($arr2); ?>,
<?php echo json_encode($arr3); ?>,
<?php echo json_encode($arr4); ?>,
<?php echo json_encode($arr5); ?>,
<?php echo json_encode($arr6); ?>,
<?php echo json_encode($arr7); ?>,
<?php echo json_encode($arr8); ?>,
<?php echo json_encode($arr9); ?>,
<?php echo json_encode($arr10); ?>,
],[
{axis:"Gesundheitszustand",value:0.63},
{axis:"BMI",value:0.58},
{axis:"Stress",value:0.67},
{axis:"Körperliche Aktivität",value:0.33},
{axis:"Nahrung: Gemüse/Obst",value:0.66},
{axis:"Nahrung: Fisch",value:0.25},
{axis:"Nahrung: Fleisch",value:0.50},
{axis:"Geistige Gesundheit",value:0.68},
{axis:"Zufriedenheit",value:0.7},
{axis:"Rauchen",value:0.91},
]
];
Although json_encode is the correct way, it has to be the data-integration, correct? Or am I missing something?
Any suggestions? Many thanks for your comments/help in advance!
Use echo to output a string directly
Related
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...
I am trying to grab my post data from my view and have it there on page reload (after it passes through validation), I am really struggling with this as I am only just learning JavaScript so anything dynamic to my is completely new...
What the data looks like in a print_R():
Array ( [firstname] => [lastname] => [address1] => [address2] => [addressSuburb] => [addressState] => [addressPostcode] => [email] => [addressCountry] => AU [orderRef] => [orderNote] => [orderTrack] => [counter0] => 0 [itemCode0] => 1234 [Desc0] => Test1 [Qty0] => 1 [Cost0] => 5 [counter1] => 1 [itemCode1] => 5678 [Desc1] => Test 2 [Qty1] => 2 [Cost1] => 10 [create] => Create Order )
What my current view loops look like:
<?php if($this->input->post()):?>
<?php foreach($this->input->post('counter') as $counter): ?>
<tr>
<?php foreach($this->input->post() + $counter AS $key => $value): ?>
<td>
<input type="text" name="<?php echo $key + $counter ?>" value="<?php echo $value ?>"/>
</td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
<?php endif; ?>
The Error I am getting:
Severity: Warning
Message: Invalid argument supplied for foreach()
I assume its because counter isnt actually an array, just part of it... I dont know how to output each line of entry data into its own array, then it would actually be rather easy to do...
Please don't give me a hard time for having it all in the view, as I am learning heaps easier to have it centralized there while trying to get an output.
Actually this code is wrote in index.php file but now i want to pass this javascript array value to external js file.
<?PHP
$qry2 = mysql_query("SELECT table_no FROM table_info");
while($res2 = mysql_fetch_array($qry2))
{
static $i = 0;
$i++;
$reg_table[$i] = $res2['table_no'];
}
?>
<script>
var bookedSeats = new Array();
<?php foreach($reg_table as $key => $val)
{ ?>
bookedSeats.push('<?php echo $val; ?>');
<?php }?>
</script>
I want the bookedSeats variable to be in the external table.js file.
You have jQuery tag in there, so I am going to give you this... use Ajax:
test.php
<?php
// Handle Ajax Request
if (isset($_GET['loadData']))
{
// Query your db here, im building dummy data
$results = array();
for ($i = 0; $i < 10; $i++) {
$results[] = 'Data '. $i;
}
// Return Data
exit(json_encode($results));
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
// Load Data Via Ajax
$.getJSON("test.php?loadData", function(bookedSeats)
{
console.log(bookedSeats);
});
</script>
When the page loads, we get the result like this:
<script>
var bookedSeats = new Array();
<?php foreach($reg_table as $key => $val)
{ ?>
bookedSeats.push('<?php echo $val; ?>');
<?php }?>
</script>
This can be greatly simplified and made immune to XSS:
<script>
var bookedSeats = <?php echo json_encode(array_values($reg_table)); ?>;
</script>
You can now refer to bookedSeats in your external .js file, but only if that file is being run after this inline script has been placed. In other words, putting:
<script src="external.js"></script>
after the <script>...<?php ... ?>...</script> is okay, but putting it before is only okay if you are deferring its execution - it's just safer to put it after ;)
I have an alternative solution for you eventually even if Latheesan Kanes's one is right.
Mine is just given as a trivial exemple if you have access to a constructor in your Javascript object in the table.js file.
<script>
var bookedSeats = new Array();
person=new Object();
<?php foreach($reg_table as $key => $val)
{
// here a javascript object
?>
person.firstname="John"; // of course replace firstname and John by your informations
<?php }?>
// then call table.js constructor
var objectInTableDotJS = new YourConstructor(person); // now in table.js you need to make modification :)
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;
?>
I have a project i am working on that requires sending information from database through a php script using json feed to javascript. Here are the scripts:
This is the javascript:
<link rel= 'stylesheet' type='text/css' href='fullcalendar/fullcalendar/fullcalendar.css' />
<link rel="stylesheet" media="print" href="fullcalendar/fullcalendar/fullcalendar.print.css" />
<script type="text/javascript" src="fullcalendar/lib/jquery.min.js"></script>
<script type='text/javascript' src="fullcalendar/fullcalendar/fullcalendar.js"></script>
<script type="text/javascript" src="fullcalendar/lib/jquery-ui.custom.min.js" ></script>
<script>
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: true,
events: "public_calendar.php"
})
});
</script>
</head>
<body>
<div id='calendar'></div>
</body>
</html>
?php require_once("includes/initialize.php"); ?>
<?php require_once(LIB_PATH.DS.'database.php'); ?>
<?php
//Find all the events
$events = Event::find_all();
foreach($events as $event):
$id = (int) $event->id;
$title = "{$event->event_title}";
$start = "{$event->start_date}" ." ". "{$event->start_time}";
$end = "{$event->end_date}" ." ". "{$event->end_time}";
$url = "event_detail.php";
echo json_encode( array(
'id' => $id,
'title' => "{$title}",
'start' => "{$start}",
'end' => "{$end}",
'url' => "{$url}"
));
endforeach;
?>
This is how the php script should look like:
[ {"id":111,"title":"Event1","start":"2013-10-10","url":"http:\/\/yahoo.com\/"},
{"id":222,"title":"Event2","start":"2013-10-20","end":"2013-10-22","url":"http:\/\/yahoo.com\/"}
]
This is how it looks like now:
{"id":12,"title":"Matriculation","start":"2013-11-5 08:00","end":"2013-11-5 17:00","url":"event_detail.php"}
{"id":13,"title":"Exam","start":"2013-11-30 09:00","end":"2013-11-30 16:00","url":"event_detail.php"}
{"id":2,"title":"Convocation","start":"2013-12-11 08:00","end":"2013-12-11 19:00","url":"event_detail.php"}
Thanks for your help in advance.
The best way to achieve the result you want is to create an array in PHP, then use json_encode() to create the output. You're already doing some of this - you just need a little more:
<?php
//Find all the events
$events = Event::find_all();
$eventList = array(); // Assemble list of all events here
foreach($events as $event):
$eventList[] = array( // Add our event as the next element in the event list
'id' => (int) $event->id,
'title' => $event->event_title,
'start' => $event->start_date." ".$event->start_time,
'end' => $event->end_date." ".$event->end_time,
'url' => "event_detail.php"
);
endforeach;
echo json_encode($eventList); // encode and output the whole list.
?>
I've also simplified and shortened some of your code to remove the unnecessary double quotes.