Fullcalendar get events with jquery and PHP - php

I'm using JQuery FullCalendar version 1.5.4 and I want to set the events with JQuery.
I use $.getJSON to call a php file, that retreive my data in my MySQL database.
When I limit my query with limit 0,1 , everything works fine. The event is sucessfully displayed in the calendar. However, when my php return an array of object, I get the error : Uncaught TypeError: Cannot call method 'replace' of null
the JSON data returned by my PHP Page looks like this :
[{"id":1,"title":"Halloween ","start":"2013-02-08 00:00:00","end":"2013-02-08 00:00:00","allDay":true},{"id":2,"title":null,"start":"2013-02-12 00:00:00","end":"2013-02-12 00:00:00","allDay":true},{"id":3,"title":"Sortie Valcartier","start":"2013-02-20 00:00:00","end":"2013-02-20 00:00:00","allDay":true}]
The PHP code looks like this :
<?php
//header('content-type: application/json; charset=utf-8');
mysql_connect("localhost","root") or die (" NOPE . [" . mysql_error() . "]");
mysql_select_db("garderie");
$query = "select a.ActiviteID as ActiviteID,a.nom as Nom , cd.datedujour as Jour from activites a
inner join calendrieractivite ca
on a.activiteid = ca.activiteid
inner join calendrierdate cd
on ca.dateid = cd.dateid
";
$result = mysql_query($query);
$events = array();
$i = 0;
$year = date('Y');
$month = date('m');
while($ligne = mysql_fetch_array($result))
{
$id = $ligne["ActiviteID"];
$nom = $ligne["Nom"];
$e = array(
'id' => (int)$id,
'title' => $nom,
'start' => $ligne["Jour"],//$start,
'end' => $ligne["Jour"],
'allDay' => true
);
$events[$i] = $e;
$i++;
}
mysql_close();
echo (json_encode($events));
?>
the jquery code looks like this
...
$.getJSON('json_events.php', null, function(data){
$('#calendar').fullCalendar({
events: data,
...

You'll need to filter your events on the php side, and make sure every event has a title. When you pass a null title to FullCalendar, it seems to break the script.
{"id":2,"title":null,"start":"2013-02-12 00:00:00","end":"2013-02-12 00:00:00","allDay":true}

Related

PDO fetch returning zero

I have this code which i am testing from last couple of hour but unable to understand that why TodayAttendanceCount is not returning 0.
$sqlCheckLoginEntryCount = "SELECT Count(*) TodayAttendanceCount FROM AttendanceMachineLogin
WHERE Date(RecordAddDateTime) = :RecordAddDateTime
AND TimeTrackId = :TimeTrackId";
$statementEntryCount = $connPDO->prepare($sqlCheckLoginEntryCount);
$queryParams = array(
':TimeTrackId' => $TimeTrackId,
':RecordAddDateTime' => $RecordAddDateTime
);
$statementEntryCount->execute($queryParams);
$queryData = $statementEntryCount->fetch();
echo '\n ';
//var_dump($queryData);
echo "\n Attendance Count". $queryData['TodayAttendanceCount'] ." ;";
I have executed the same query in MySqlWorkbench which is working fine and there is data and it is fine from the database side.
Remove : part at the $queryParams. It isn't needed. The code will look like this.
$queryParams = array(
'TimeTrackId' => $TimeTrackId,
'RecordAddDateTime' => $RecordAddDateTime
);
Try this:
$sqlCheckLoginEntryCount = "SELECT Count(*) As TodayAttendanceCount FROM AttendanceMachineLogin
WHERE Date(RecordAddDateTime) = ':RecordAddDateTime'
AND TimeTrackId = :TimeTrackId";
$statementEntryCount = $connPDO->prepare($sqlCheckLoginEntryCount);
$queryParams = array(
'TimeTrackId' => $TimeTrackId,
'RecordAddDateTime' => $RecordAddDateTime
);
$statementEntryCount->execute($queryParams);
$queryData = $statementEntryCount->fetch(PDO::FETCH_ASSOC);
echo '\n ';
//var_dump($queryData);
echo "\n Attendance Count ". $queryData['TodayAttendanceCount'];
Hope I pushed you further.

Why is my php returning an empty JSON array?

I'm trying to get Json data from Mysql using the following code. I've verified that the columns being selected exist.
I've searched several sites including SO and haven't noticed anything wrong with it.
I've used the example answer given in the following question:
Here
global $mysqli;
$response = array('faqtbl' => array());
// Query Db
$query = "SELECT ticketID, agentName FROM faqtbl";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$response['faqtbl'][] = array(
'ticketID' => $row['ticketID'],
'agentName' => $row['agentName']
// 'name' => $row['name']
// 'number' => $row['number'],
// 'address' => $row['address'],
);
}
}
// I've added this but it doesn't help
//header('Content-Type: application/json');
echo json_encode($response);
If I remove 'agentName' => $row['agentName'] it works and pulls the data in this manner:
{"faqtbl":[{"ticketID":"8"},{"ticketID":"12"},....
I'm using the following: php 5.5.9, apache 2.4.7
Edit Update:
If I use the following within my while loop I get correct Data (without the json encode line):
echo "ticket: " . $row["ticketID"]. " " . $row["agentName"]." " .$row["ticketDate"]. "<br>";
Use json_last_error()
It should tell the problem.
Also you can use json_last_error_msg()
Most possible that your agent field contains some forbidden characters.

Create array in php and use Jquery get

I'm trying to make a call to the database and recieve a "toplist" that is limited to 10 in PHP. Here I need to make an array and give it back to the Jquery with $.get().
But it's failing in recieving all the data with this code, How can I make this to be recieved and then do a "for each" in the Jquery for all the data that is being sent back from the PHP?
Jquery:
$.get("core.inc.php?get_toplist=1",
function(data) {
var json = JSON.parse(data);
alert(json['name']);
});
PHP:
if ($_GET['get_toplist']) {
$get_top_list = mysql_query("
SELECT * FROM ".$DBprefix."Submissions
WHERE status='1'
ORDER BY points DESC LIMIT 10");
$i = 0;
$arr = array();
while ($top_list = mysql_fetch_array($get_top_list)) {
$arr[] = array(
'position' => $i++,
'name' => $top_list['name'],
'points' => $top_list['points']
);
}
echo json_encode($arr);
}
You're returning an array, but your Javascript code is treating it as a single element. Try:
alert(json[0].name);
If you want a foreach, you can do:
$.each(json, function(i, el) {
console.log(el.name + " score is " + el.points);
});
Friend your json will be like .
[{"position":1,"name":"name1","points":"points"},{"position":2,"name":"name2","points":"points"}, {"position":3,"name":"name3","points":"points"},....]
so you can not directly access it like ur way.
make a loop then access it.
$.each(data,function(i,val){
alert(val.name);
});
this will work.
your php code is not proper
if ($_GET['get_toplist']) {
$get_top_list = mysql_query("
SELECT * FROM ".$DBprefix."Submissions
WHERE status='1'
ORDER BY points DESC LIMIT 10");
$i = 0;
$arr = array();
while ($top_list = mysql_fetch_array($get_top_list)) {
$arr[] = array(
'position' => $i++,
'name' => $top_list['name'],
'points' => $top_list['points']
);
}
}
echo json_encode($arr);
}
just add '}' before echo json_encode($arr);
also you are getting an array change in alert(json[0]['name']);

How to return latest Mysql entry through JQuery/Ajax request

I am trying to pull the latest entry of a mysql table through ajax and display it as html content inside a div. I have ajax and php functioning correctly, the only problem I have is that I want to query for new entries and stack the results at a time interval within a loop and I've run into two problems: getting the data to behave like a normal javascript string, and getting the loop to only return unique entries.
update.php file
$con=mysqli_connect("mydbhost.com","username","password","database_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM conversations");
$j = 0;
while($row = mysqli_fetch_array($result))
{
$carray[j] = $row['comment'];
$j++;
}
$comment = (array_pop($carray));
echo $comment;
echo "<br>";
mysqli_close($con);
JQuery Ajax request loop:
$(document).ready(function(e){
var comment;
function commentLoop() {
comment = $('#testdiv').load('update.php');
$('#testdiv').append(comment);
setTimeout(commentLoop, 6000);
}
commentLoop();
$(document).focus();
});
The problem is by doing SELECT * FROM conversations you keep requesting whole table -- although you only take the last one.
Your code need to remember which comment has been loaded, and only get any comment newer than that.
For example, assuming your primary key is incremental, do SELECT * FROM conversations WHERE convid > ?. Replace ? with latest comment that has been loaded. If you're loading for the first time, just do SELECT * FROM conversations
You could pass the last comment id displayed using request parameter into update.php. Also I recomment returning the data in JSON format so you can return a collection of comment and id and parse it easily
This will count the comments in the table and select the last entered comment then pass them to ajax as json data only if the received count is lower than the count of the comments in the table:
PHP:
if(isset($_GET['data']))
{
$con = new mysqli('host', 'user', 'password', 'database');
$init_count = $_GET['data'];
$stmt1 = "SELECT COUNT(*) AS count FROM conversations";
$stmt2 = "SELECT comment FROM conversations ORDER BY date_column DESC LIMIT 1";
$total = $con->prepare($stmt1);
$total->execute();
$total->bind_result($count);
$total->fetch();
$total->close();
if( ($init_count != '') && ($init_count < $count) )
{
$lastComment = $con->prepare($stmt2);
$lastComment->execute();
$result = $lastComment->get_result();
$row = $result->fetch_assoc();
$lastComment->close();
$data = array(
'comment' => $row['comment'],
'count' => $count
);
}
elseif($init_count == '')
{
$data = array(
'comment' => '',
'count' => $count
);
}
$pdo->close();
echo json_encode($data);
}
HTML:
<input type="hidden" id="count" value="" />
JQUERY:
$(document).ready(function(e){
function getComment(){
var count = $('#test').val();
$.ajax({
type: 'get',
url: 'update.php?data=' + count,
dataType: 'json',
success: function(data)
{
$('#count').val(data.count);
if(data.comment) != $('#testdiv').html(data.comment);
}
});
}
getComment();
setInterval(getComment, 6000);
});
SELECT * FROM conversations order by insert_date desc limit 10
insert_date the date time comment is inserted, i hope you will have a field for storing that if not add it now

How best do I implement mysql data into a line of javascript code?

I am modifying some javascript for Google maps so that the different pin information is retrieved from my database. If I was to do this with just php it would be like this:
<?php while($row = mysql_fetch_assoc($query))
{$title = $row['title']; $desc = $row['desc']; echo 'This '.$title .' and this '. $desc .';}?>
If there were 5 rows in the database there will be five lines with 5 different titles and descriptions.
But I have this line of javascript that I would like to be in a while loop:
map.addMarkerByLatLng(37.8685, -1.5108, "Sanatario de Terburculosos", createInfo("title goes here",""));
How can i write it so that that javascript is in a php while loop or how can i do the javascript equivelant of the php while loop so that i can retrieve multiple rows of lang,lat info each in its own javascript code like above?
Thank you.
ajax.php
<?php
$obj = array();
while($row = mysql_fetch_assoc($query)){
$obj[] = new array(
"title" => $row["title"],
"desc" => $row["desc"],
"lat" => $row["lat"],
"lon" => $row["lon"]
);
}
echo json_encode($obj);
?>
jquery ajax
$.getJSON("ajax.php",function(data){
for(var i=0;i<data.length;i++){
map.addMarkerByLatLng(
data[i].lon,
data[i].lat,
data[i].description,
createInfo(data[i].title,""));
}
});
Combine the two code examples you have provided:
<?php
$pinTpl = 'map.addMarkerByLatLng( %s , %s , "%s" , createInfo( "%s" , "" ) );';
while( $row = mysql_fetch_assoc( $query ) ){
echo sprintf( $pinTpl ,
$row['lat'] , # Where 'lat' is the field name for the latitude in DB
$row['long'] , # Where 'long' is the longitude field name in DB
$row['title'] , # The title
$row['desc'] # The description
)."\n"; # A newline, for readability
}
?>

Categories