Javascript with PHP Foreach - javascript

So I am trying to use this plugin: http://w3widgets.com/responsive-calendar/
And the way the calendar is initialized and have events added is like so:
<script>
<?php $today = date('Y-m'); ?>
$( document ).ready( function() {
$(".responsive-calendar").responsiveCalendar({
time: '<?php echo $today; ?>',
events: {
"2014-04-30": {"number": 1, "badgeClass": "badge-warning", "url": "http://w3widgets.com/responsive-calendar"},
"2013-04-26": {"number": 1, "badgeClass": "badge-warning", "url": "http://w3widgets.com"},
"2013-05-03": {"number": 1, "badgeClass": "badge-error"},
"2013-06-12": {}}
});
});
</script>
I want to generate the events with a foreach because the events are all stored in a database. I tried to do the following:
events: {
<?php foreach($events as $event): ?>
"<?php echo $event->date; ?>"...
But I get an error that says the ) in the ($events as $event) is unexpected.
How can I do this, I must be able to or the calendar has to disappear. Plain and simple.
UPDATE
If I var_dump() the $events I get the following string (shortened to the first event!)
array(3) { [0]=> object(stdClass)#21 (5) { ["id"]=> string(1) "1" ["name"]=> string(17) "State Large Group" ["school"]=> string(9) "NHS Bands" ["date"]=> string(9) "4-16-2014" ["showHome"]=> string(1) "1" }...
And If I events: <?php echo json_encode($events); ?> it doesn't encode in the correct order. It does:
events: [{"id":"1","name":"State Large Group","school":"NHS Bands","date":"4-16-2014","showHome":"1"},{"id":"2","name":"State Solo\/Ensemble","school":"NHS Bands","date":"4-26-2014","showHome":"1"},{"id":"3","name":"League Music Festival","school":"RVMS Bands","date":"4-29-2014","showHome":"1"}] });
When it needs to be something like:
"2013-06-12": {}

events: <?php echo json_encode($events) ?>

You can convert your database result to json and pass it to events.
JSON encode MySQL results

Related

how to make new line in javascript

I search for some code, even I found it, but I dunno how to add a new line of the javascript he creates.
The original link is this, I have some problem in code bellow. Because I have change the code "price": "120.00", to "price": "\\using php to call some data",.
This is original code:
{
"product_id": "1",
"store_id": "1",
"price": "120.00",
"sequence": "0",
"id": "1",
"parent_id": "0",
"name": "Store 1",
"email": "store1#store1.com"
}
This is what I wrote:
$result1=mysqli_query($conn, "select * from product");
while ($row1=mysqli_fetch_assoc($result1))
{
$pno1 = $row1["no"];
$sql1 = "SELECT * FROM xx where WHERE product_id = '$pno1') ";
$query1 = mysqli_query($conn , $sql1);
$rowcont1 = mysqli_num_rows($query1);
?>
{
"name": "<?php echo $row1["PACKAGE_NAME"]; ?>",
"id": "<?php echo $row1["PACKAGE_NAME"]; ?>",
"cat": "UNIFI",
<?php
if ($rowcont1 == 0)
{
?>
"vas": "<?php echo "No default vas"; ?>"
<?php
}
else
{
?>
"vas": "<?php
while($rowvas1=mysqli_fetch_assoc($query1))
{
echo "$rowvas1[PACKAGE_NAME]\\n\\n"; //This is the line I want to chage (\\n no function for me)
}
?>"
<?php
}
?>
},
<?php
I have found many question same with me, but even I have tried all of the solutions, my code still didn't work
Try the following instead:
echo "$rowvas1[PACKAGE_NAME]<br>";
Instead of \n just add html line-break <br>.
Edit: If you are using the JS provided in the jsfiddle, be sure to change the following line:
$('#price-store').text(pricestore[$('option:selected', this).index()].price);
to(.text( to .html():
$('#price-store').html(pricestore[$('option:selected', this).index()].price);

How I can get values of array result?

I'm new and I work in php. I have a problem, I have this "array" result from php script (this array was extracted with php of a html page):
Array ( [0] => {"autostart": false,"controls": true,"flashplayer": "/jwplayer7/jwplayer.flash.swf","image": "I NEED THIS", ga: {}, "mute": false, "ph": 1, "preload": "none", "primary": "html", "repeat": false, "skin": { "name": "tube" }, "stagevideo": true, "stretching": "uniform", "visualplaylist": true, "width": "100%", "aspectratio": "16:9", "provider": 'http', "startparam": "start", tracks: [{"file":"I WANT THIS","kind":"thumbnails"}], "sources": [{"file":"I NEED THIS","label":"480p"},{"file":"I NEED THIS","label":"720p"},"I WANT THIS"] ,"logo": {"logoBar": "I NEED THIS", "target": "blank","link": ""},"displaydescription": false,"displaytitle": false , "abouttext": "RapTu Player", "aboutlink": "" } )
I only need the values from image:, sources:[{"file";}} but I can't get the values, nothing, I try with javascript:
var str = '<?php echo $jw; ?>';
var json = JSON.parse(str);
var parse = $.parseJSON(file);
$jw is the variable of the array, and I don't have any result, nothing is printed. Could you help me? (Sorry for my english).
Upgrade: I resolved it using:
object = [<?php echo $jw; ?>]
for(f=0;f<object.length;f++){
}
Thanks everybody!
if you want doing that.
Then use
var json = '<?php echo json_encode($jw); ?>';
and in json variable you have json from array
or if you only sources you can use
var json = '<?php echo json_encode($jw[0]["sources"]); ?>';
but only work with first element in array $jw
In php:- encode string in php properly
$json = json_encode('{"autostart": false,"controls": true,"flashplayer": "/jwplayer7/jwplayer.flash.swf","image": "I NEED THIS", ga: {}, "mute": false, "ph": 1, "preload": "none", "primary": "html", "repeat": false, "skin": { "name": "tube" }, "stagevideo": true, "stretching": "uniform", "visualplaylist": true, "width": "100%", "aspectratio": "16:9", "provider": "http", "startparam": "start", tracks: [{"file":"I WANT THIS","kind":"thumbnails"}], "sources": [{"file":"I NEED THIS","label":"480p"},{"file":"I NEED THIS","label":"720p"},"I WANT THIS"] ,"logo": {"logoBar": "I NEED THIS", "target": "blank","link": ""},"displaydescription": false,"displaytitle": false , "abouttext": "RapTu Player", "aboutlink": ""}');
$array1 = array($json);
Pass $array1 to html in script:-
var str = '<?php echo $jw; ?>'; // echo $array1[0] as $jw
var json = JSON.parse(str);
var parse = $.parseJSON(file);

Get data highchart from php table

i want to show every row data from my table to highchart, how can i show that data using php to javascript foreach row?
<script>
series: [{
name: 'Mie Instan',
data: [<?php foreach ($query as $row){echo $row['mie'];}]
}, {
name: 'Beras',
data: [<?php foreach ($query as $row){echo $row['beras'];}]
}, {
name: 'Telur',
data: [<?php foreach ($query as $row){echo $row['telur'];}]
}]
</script>
What I would do, in order to get the HighCharts data arranged as an array of numerical values, is to use php array_push and PHP foreach to sort the data in three different PHP arrays.
<?php
// Declare 3 new arrays.
$mie=[];
$beras=[];
$telur=[];
// Fill the arrays with the database values
foreach ($query as $row){
array_push($mie, $row['mie']);
array_push($beras, $row['beras']);
array_push($telur, $row['telur']);
}
?>
Then use the arrays to produce a string of "coma separated values" in the HighCharts script, using PHP join, like this:
<script>
series: [{
name: 'Mie Instan',
data: [<?php echo join(",", $mie); ?>]
}, {
name: 'Beras',
data: [<?php echo join(",", $beras); ?>]
}, {
name: 'Telur',
data: [<?php echo join(",", $telur); ?>]
}]
</script>
Hoping this helps...
;)

JSON from php into JS file

I'm trying to draw DB tables using php PDO which i successfully made using the following code:
test.php
<?php
$dbh = new PDO("mysql:host=localhost;dbname=test", "root", "");
$statement=$dbh->prepare("SELECT * FROM pdotable");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
?>
I need to take the results into a chart JS code which his data array is in this code:
initCharts: function() {
if (Morris.EventEmitter) {
// Use Morris.Area instead of Morris.Line
dashboardMainChart = Morris.Area({
element: 'sales_statistics',
padding: 0,
behaveLikeLine: false,
gridEnabled: false,
gridLineColor: false,
axes: false,
fillOpacity: 1,
data:
[{
period: '2011',
sales: 1400,
profit: 400
}, {
period: '2011 Q2',
sales: 1100,
profit: 600
}, {
period: '2011 Q3',
sales: 1600,
profit: 500
}, {
period: '2011 Q4',
sales: 1200,
profit: 400
}, {
period: '2012 Q1',
sales: 1550,
profit: 5
}],
lineColors: ['#399a8c', '#92e9dc'],
xkey: 'period',
ykeys: ['sales', 'profit'],
labels: ['Sales', 'Profit'],
pointSize: 0,
lineWidth: 0,
hideHover: 'auto',
resize: true
});
}
},
How do i replace the data : [json] with the JSON from the PHP result?
In php file after closing tag you need write JS part, like it
<script type="text/javascript" charset="utf-8">
var data = <?php echo json_encode($results); ?>;
</script>
Be careful with the semicolon. Just need to correct a little JS script, but I think you can do it.
You would need to echo out the content type, so that browser sees return data and accept as json.
echo ('Content-type: application/json');
$json = json_encode($results);
echo $json;
I usually open up the google console, or firefox's firebug to see the response tab on the network tab you've sent to. From there, you can see what data you are getting back from server to check if you are echoing right data or not.
Furthermore, you can print them in console log by pluggin
console.log(data);
Within your javascript to confirm whether you are getting data in right format.
You might as well look upon some db document to pull out data just what you need.
Instead of SELECT * FROM pdotable, SELECT period, sales, profit would do.
Hope this helps.
// test.php
$dbh = new PDO("mysql:host=localhost;dbname=test", "root", "");
$statement=$dbh->prepare("SELECT * FROM pdotable");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
header('Content-type: application/json');
echo $json;
//js
...
if (Morris.EventEmitter) {
//if you use jQuery
$.get('/test.php', {}, function(result) { //or use $.getJSON
dashboardMainChart = Morris.Area({
...
data: result,
...
xmlhttp if you not use jQuery
you only need this json_encode function
this accept an array as parameter and return a string json that you can insert inside a js code simple use echo function
the js code must insert in php file and not in external js

How to loop through data from php in javascript?

I want to ask how to the repeat a region in javascript?
The data are dynamic and I want to find all items through php do...while loop:
<script type="text/javascript">
window.onload = function () {
<?php do{ ?>
var chart<?php echo $row_RecAllAnswers['q_id']; ?> = new CanvasJS.Chart("<?php echo $row_RecAllAnswers['q_id']; ?>", {
theme: "theme2",//theme1
title:{
text: "No. " + "<?php echo $row_RecAllAnswers['q_id']; ?>"
},
animationEnabled: true, // change to true
data: [
{
// Change type to "bar", "splineArea", "area", "spline", "pie",etc.
type: "column",
dataPoints: [
{ label: "A" , y: <?php echo $row_RecAllAnswers['A']; ?> },
{ label: "B", y: <?php echo $row_RecAllAnswers['B']; ?> },
{ label: "C", y: <?php echo $row_RecAllAnswers['C']; ?> },
{ label: "D", y: <?php echo $row_RecAllAnswers['D']; ?> }
]
}
]
});
chart<?php echo $row_RecAllAnswers['q_id']; ?>.render();
chart<?php echo $row_RecAllAnswers['q_id']; ?> = {};
window.alert(<?php echo $row_RecAllAnswers['q_id']; ?>);
<?php } while ($row_RecAllAnswers = mysql_fetch_assoc($RecAllAnswers)); ?>
}
</script>
Use json_encode to convert your mysql query result to JSON.
Write the JSON to your HTML.
In Javascript use a foreach on the JSON array to iterate.
json encode that php array into a javascript variable and then loop through that variable. In twig I do it like this:
var objectName = {{ phpVariable|json_encode|raw }};
so I think this should work find in PHP (did not test it):
var objectName = <?php echo json_encode($phpVariable); ?>;
Then the javascript variable 'objectName' will contain your data and now you can use regular javascript to loop through the data. You can also use underscore as it is easier.
_.each(objectName, function(item, key){
//do stuff here
});

Categories