I am new to json .I am getting the data from php code in json format..
[
{
"Title": "New Event",
"TYPE": "info",
"StartsAt": "16 November 201512:00",
"EndsAt": "25 November 201512:00"
},
{
"Title": "Party",
"TYPE": "warning",
"StartsAt": "25 November 2015 09:30",
"EndsAt": "25 November 2015 5:30"
},
]
I have a javascript file demo.js
I want to receive this data in js file, currently the data is hardcoded. I want to show the events which I fetch from db.
vm.calendarView = 'month';
vm.calendarDay = new Date();
vm.events = [
{
title: 'An event',
type: 'warning',
//startsAt: moment().startOf('week').subtract(2, 'days').add(8, 'hours').toDate(),
//endsAt: moment().startOf('week').add(1, 'week').add(9, 'hours').toDate(),
startsAt:new Date(2015,10,1,1),
endsAt:new Date(2013,5,1,1),
draggable: true,
resizable: true
}, {
title: '<i class="glyphicon glyphicon-asterisk"></i> <span class="text-primary">Another event</span>, with a <i>html</i> title',
type: 'info',
startsAt: moment().subtract(1, 'day').toDate(),
endsAt: moment().add(5, 'days').toDate(),
draggable: true,
resizable: true
}, {
title: 'This is a really long event title that occurs on every year',
type: 'important',
startsAt: moment().startOf('day').add(7, 'hours').toDate(),
endsAt: moment().startOf('day').add(19, 'hours').toDate(),
recursOn: 'year',
draggable: true,
resizable: true
}
];
If the question is roughly "How do I get data from my database and output it as JSON in Javascript" then hopefully the following pseudo code will guide you in the right general direction.
<?php
include 'db.php';
$json=array();
/* Query the db */
$sql='select * from `events`;';
$res=$db->query( $sql );
if( $res ){
while( $rs=$res->fetch_object() ){
$json[]=array(
'title' => $rs->title,
'type' => $rs->type,
'startsAt' => $rs->startsAt,
'endsAt' => $rs->endsAt,
'draggable' => $rs->draggable,
'resizable' => $rs->resizable
);
}
}
$db->close();
$js_json_var=json_encode( $json, JSON_FORCE_OBJECT );
?>
<html>
<head>
<title></title>
<script>
var json=<?php echo $js_json_var;?>;
/* Other js code */
</script>
</head>
<body>
<h1>json</h1>
</body>
</html>
Javascript: AJAX request:
var events;
$.ajax({
url: '/data.php',
success: function(data){
events = JSON.parse(data);
}
});
data.php is like this
$db = new PDO(/* init connection here */);
print json_encode($db->query('select * from `tablename`')->fetchAll(PDO::FETCH_ASSOC));
// In javascript
$.ajax({
type: 'post',
url: 'data.php',
data: 'data',
cache: false,
success: function(data)
{
console.log(data);
}
});
// In data.php
header('Content-type: application/json');
$data = array();
$sql = "SELECT * FROM TABLE_NAME";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res))
{
$data[] = $row;
}
echo json_encode($data, true);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.