Database query with fullcalendar - php

OK I'm trying to pull events from a MySQL database to populate a calendar. The start times are stored in Unix time so I have used the following events source.
events: {
url: '/php/booking_events.php',
type: 'POST',
data: {
start: start.unix(),
end: end.unix(),
branch: branch.id_office,
instrument: inst
},
error: function() {
alert('there was an error while fetching events!');
},
}
This brings up the first problem, when I run this I get an error in dev tools saying start is not defined? Doesn't the calendar automatically generate the start and end times?
Secondly, if I manually enter parameters into my PHP it generates a JSON array then echoes it back but the script is constantly saying 'there was an error while fetching events!'
<?php
require_once('../Connections/localhost.php');
require_once("../Includes/functions.php");
//if (!isset($_POST['start']) || !isset($_POST['end'])) {
// die("Please provide a date range.");
//}
//$range_start = parseDateTime($_POST['start']);
//$range_end = parseDateTime($_POST['end']);
//$branch = GetSQLValueString($_POST['id_office'], "int");
//$inst = GetSQLValueString($_POST['instrument'], "int");
$range_start = '1433462401';
$range_end = '1433721599';
$branch = 2;
$inst = 3;
// Parse the timezone parameter if it is present.
$timezone = null;
if (isset($_POST['timezone'])) {
$timezone = new DateTimeZone($_POST['timezone']);
}
// Query database to get events
mysql_select_db($database_localhost, $localhost);
$query_Events = sprintf("SELECT hm_classes.datetime, hm_classes.id_student, hm_classes.inst FROM hm_classes INNER join hm_rooms ON hm_classes.id_room = hm_rooms.id_room WHERE datetime BETWEEN %s AND %s AND id_office = %s AND inst = %s", $range_start, $range_end, $branch, $inst);
$Events = mysql_query($query_Events, $localhost) or die(mysql_error());
while ($row = mysql_fetch_assoc($Events)){
$id = $row['id_class'];
$title = 'Booking';
$start = date('c', $row['datetime']);
$end = date('c', ($row['datetime'] + hoursToSecods($row['Session'])));
$input_arrays[]= array(id => $id, title => $title, start => $start, end => $end, allDay =>'false');
}
// Send JSON to the client.
echo json_encode($input_arrays);
?>
The echoed result of this is
[{"id":"1","title":"Booking","start":"2015-06-05T14:00:00+02:00","end":"2015-06-05T15:00:00+02:00","allDay":"false"}]
which is what I think fullcalendar is after? Any help would be greatly appreciated.

OK I think I have solved this problem, following kamlesh.bar's suggestion I went to look at http://www.jqueryajaxphp.com/fullcalendar-crud-with-jquery-and-php/.
After looking through his code I separated my AJAX request out from the main fullcalendar script and gave it it's own function.
function getEvents(){
$.ajax({
url: 'booking_events.php',
type: 'POST', // Send post data
data: {type: 'fetch',
branch: $('#branch').val(),
inst: $('#instrument').val()},
async: false,
success: function(s){
json_events = s;
}
})
}
Then in fullcalendar I set the events as
events: JSON.parse(json_events),
This is now allowing the results generated by the php to be entered into the calendar.
As for that start: stat.unix() issue, I am just using strtotime in php to change that to a Unix timeformat

Related

Ajax failing multiple times before it works

I have a very annoying bug. My AJAX queries are failing anywhere up to 20-30 times with 500 GET and POST server errors, but then all of a sudden they work.
It seems to be completely random, as sometimes I will load the page and it will work fine for a full day of usage, but then the next day it will fail and I have to catch and retry it up to 30 times to get it to work.
AJAX
function getData(){
//Get Data and build contributions Table
$.ajax({
url: 'assets/processes/dash/support/get-data.php', // URL of php command
tryCount : 0,
retryLimit : 3,
type: 'POST', //TYPE
data: {'id': id}, //Variables in JSON FORMAT
success: function(results) { //SUCCESSFUL REQUEST FUNCTION
var result = $.parseJSON(results);
console.log(result);
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
$.ajax(this);
return;
} else {
//handle error
}
}
}); // end ajax call
PHP
<?php
include "../../../includes/database.php";
$totalOpen = $db->pdo_query_assoc("xdGetTotalUnresolvedTickets
1,0,0,0,0,0");
$totalWaitState = $db->pdo_query_assoc("xdGetWaitState 1,0,0,0,0,0");
$nonWaitState = $totalOpen['xdGetTotalUnresolvedTickets'] -
$totalWaitState['xsGetWaitState'];
$getStaff = $db->query("SELECT * FROM user WHERE role = 'Technical
Support'");
$getStaffArray = array();
foreach($getStaff as $key => $value){
$sqlUsername = $value['sqlName'];
$pdo_today = $db->pdo_query_assoc("xsGetTotalResolvedTicketsToday
'$sqlUsername'");
$start = date('Y-m-d ', strtotime('-7 days'));
$end = date('Y-m-d ', strtotime('+1 days'));
$pdo_last_week = $db->pdo_query_assoc("xsGetTotalResolvedTicketsToday
'$sqlUsername','$start','$end'");
$getCompletionRate = $db->pdo_query_assoc('xStaffTicketCompletionRate
"'.$sqlUsername.'"');
$getWeeklyRate = $db->pdo_query_assoc('xLastSevenPreviousSeven
"'.$sqlUsername.'"');
$getStaffArray[$key]['staffName'] = $value['user'];
$getStaffArray[$key]['staffFullName'] = $value['name'];
$getStaffArray[$key]['colourScheme'] = $value['colourScheme'];
$getStaffArray[$key]['today'] =
$pdo_today['xsGetTotalResolvedTicketsToday'];
$getStaffArray[$key]['thisWeek'] =
$pdo_last_week['xsGetTotalResolvedTicketsToday'];
$getStaffArray[$key]['completionRate'] = $getCompletionRate['Level'];
$getStaffArray[$key]['thisTimeLastWeek'] =
round($getWeeklyRate['Percentage'],1);
$getStaffArray[$key]['weeklyRateLevel'] = $getWeeklyRate['Level'];
$getStaffArray[$key]['weeklyPrevious7'] = $getWeeklyRate['Previous 7
Days'];
$getStaffArray[$key]['weeklyEarlier7'] = $getWeeklyRate['Earlier 7
Days'];
}
$tickets = array('totalCurrent' => $totalOpen, 'totalWaitState' =>
$totalWaitState, 'totalNoneWaitState' => $nonWaitState);
$allData = array('totalTickets' => $tickets, 'staff' => $getStaffArray);
echo json_encode($allData, JSON_FORCE_OBJECT);
?>
I know at the moment the trycount doesnt work properly, as instead of trying 3 times it tries unlimited amount until it works. Any one have any ideas as to why this could be happening?
They always fail on the php file, like the query cant be executed.
ERROR
GET http://mysite/get-events.php 500 (Internal Server Error)
jquery.min.js:4

Comparing current datetime with datetime from database without refreshing page

I want to make a simple reminder which displays something when the current date and time matches an entry in a database, without refreshing the page.
I have two entries in my database in a table called date:
date (stores reminder date) which is type DATE and
time (stores reminder time) which has type TIME.
The page reminder.php fetches the date and time stored in database and converts it into Timestamp.
This page also converts the current date and time into Timestamp using strtotime("now").
It displays both date and time when both values match by continuously refreshing the page every second.
I want to compare both values without refreshing the reminder.php page.
reminder.php
<?php
require_once 'php/database.php';
date_default_timezone_set('Asia/Kolkata');
$current = strtotime('now');
$stmt = $db->query("SELECT * FROM date");
$row = $stmt->fetchall(PDO::FETCH_ASSOC);
foreach ($row as $key) {
$dateTime = $key['date'] . $key['time'];
$dateTime = strtotime($dateTime);
}
if ($dateTime == $current) {
echo "both date and time are same";
}
else {
echo "both date and time are not same";
}
If I understands right then you need to check date from the database and current date without refreshing the page use this code ,
HTML Part :
<button id="data_pass" name="btn" >BUTTON</button>
JQuERy :
$(document).ready(function() {
$("#data_pass").click(function() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = yyyy+'-'+mm+'-'+dd;
$.ajax({
url : 'test.php',
type : 'post',
data : {"today":today},
success : function(data) {
alert(data);
},
error : function(data) {
alert("error");
}
});
});
});
PHP Part :
include('db_con.php');
class date_check extends db_connection {
function dates() {
$con = $this->db_con();
$sel = $con->prepare("select * from dates");
$exe = $sel->execute();
$dates = $_POST['today'];
foreach ($sel as $select) {
if ($select['date_i'] == $dates) {
echo "Happy BirthDay";
}
}
}
}
$obj = new date_check;
$obj->dates();
It's only for checking the date.
hope it will help you

PHP + jQuery - Long Polling with database data aren't working (it doesn't break the loop)

I'm trying to implement a long polling system on my intranetwork, most of the users use IE and some use mobile too, that's why I'm trying to do it with long polling and not with websockets.
I followed this video http://www.screenr.com/SNH and I edited some code to work with my database. (Firebird)
It all seems ok, but it just doesn't break the loop. Maybe it's a kid mistake but I cannot see it, that is why I need your help!
Here's the code:
jQuery + Ajax:
var timestamp = null;
function waitForMsg(){
$.ajax({
type: "GET",
url: "getData.php?timestamp=" + timestamp,
async: true,
cache: false,
success: function(data){
alert('It Works');
var json = eval('(' + data + ')');
timestamp = json['timestamp'];
setTimeout('waitForMsg()',15000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("A - " + XMLHttpRequest + " - error: " + textStatus + " (" + errorThrown + ")");
setTimeout('waitForMsg()',15000);
}
});
}
$(document).ready(function(){
waitForMsg();
});
</script>
getData.php ('DATAHORA' is timestamp field)
<?php
set_time_limit(0);
#ini_set("memory_limit",'64M');
require_once('../classes/conexao.php');
$banco = Conexao :: getConexao();
$sql = "SELECT FIRST 1 DATAHORA FROM AGENDAMENTOSBBM ORDER BY DATAHORA DESC";
$res = $banco->execute($sql);
$dados = $banco->fetch($res);
if($dados)
$currentmodif = $dados['DATAHORA']);
else
$currentmodif = 0;
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
while( $currentmodif <= $lastmodif ){
usleep(10000);
$sql = "SELECT FIRST 1 DATAHORA FROM AGENDAMENTOSBBM ORDER BY DATAHORA DESC";
$res = $banco->execute($sql);
$dados = $banco->fetch($res);
if($dados)
$currentmodif = $dados['DATAHORA']);
else
$currentmodif = 0;
}
$response = array();
$response['timestamp'] = $currentmodif;
echo json_encode($response);
?>
When I insert, update, or delete some data, the timestamp field are updated with the current timestamp.
I can see that the page enters the loop, but I don't know why it never ends.
Am I doing something wrong?
Thank you
I finaly found the solution.
And it was so simple. My code was not closing the connection with ibase_close
What i did was change it to close when finish the query process.
Then inside the loop, i need to reconnect the server again.
OMG how could i forgot that.
Thanks everyone.
Try replacing $currentmodif = $dados['DATAHORA']); with $currentmodif = $dados['HORA']); inside the while loop.
You're asking for an array key that doesn't exist, which will always be null, so your loop will run forever if $lastmodif is not null.
Change $currentmodif = $dados['DATAHORA']);, look:
<?php
set_time_limit(0);
#ini_set("memory_limit",'64M');
require_once('../classes/conexao.php');
$banco = Conexao :: getConexao();
$sql = "SELECT FIRST 1 DATAHORA FROM AGENDAMENTOSBBM ORDER BY DATAHORA DESC";
$res = $banco->execute($sql);
$dados = $banco->fetch($res);
if($dados)
$currentmodif = $dados['DATAHORA']);
else
$currentmodif = 0;
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
while( $currentmodif <= $lastmodif ){
usleep(10000);
$sql = "SELECT FIRST 1 DATA, HORA FROM AGENDAMENTOSBBM ORDER BY DATA DESC,HORA DESC";
$res = $banco->execute($sql);
$dados = $banco->fetch($res);
if($dados)
$currentmodif = $dados['DATA'].$dados['HORA']; // Before : $dados['DATAHORA']);
else
$currentmodif = 0;
}
$response = array();
$response['timestamp'] = $currentmodif;
echo json_encode($response);
?>
I don't know how look of your database design so, i suggest to you to change by yourself
Maybe your mistakes are on that lines. But i can't decide, because i have no time to fix it, i must do my project.
If i'm wrong, I'm sorry. Good luck
After rewriting the code in MySQL and scratching my head over why it seemed to be working just fine, I found the problem:
You need to set your initial var timestamp to 0, not null. If you set it to null, jQuery will send it as the string "null" (?timestamp=null). In PHP, it will compare this string "null" to whatever number $currentmodif is, so in the end you will never get into your while loop.
Try to eval your queries and see what they return, so you can validate the returned data and ensure the array $dados has the needed data and the keys to access any data of the array $dados.
var longpollError = false;
function longPoll(){
$.ajax({
url: "socialPolling",
type: 'GET',
dataType: 'json',
data: {param1: 'value1'},
timeout: 30000 // timeout every 10 sec
}).done(function(dataJson) {
//Success code goes here
})
.fail(function(data) {
longpollError = true; //mark this to true if there is an error
}).always(function(data) {
if(longpollError==false){ //if there is no error request it again
setTimeout(function() {
longPoll();
}, 3000);
}
})
}

returned ajax query data undefined

Hello I am attempting to create an ajax query but when my results are returned I get Undefined as a response. Except for the object called "hello" which returns back as "h" even though it is set to "hello". I have a feeling it has something to do with the way ajax is sending the data but i'm lost as to what may be the issue. Any help would be greatly appreciated.
here is the ajax
function doSearch() {
var emailSearchText = $('#email').val();
var keyCardSearchText = $('#keyCard').val();
var userNameSearchText = $('#userName').val();
var pinSearchText = $('#pin').val();
var passwordSearchText = $('#password').val();
$.ajax({
url: 'process.php',
type: 'POST',
data: {
"hello": "hello",
"emailtext": "emailSearchText",
"keycardtext": "keyCardSearchText",
"usernametext": "userNameSearchText",
"pinText": "pinSearchText",
"passwordtext": "passwordSearchText"
},
dataType: "json",
success: function (data) {
alert(data.msg);
var mydata = data.data_db;
alert(mydata[0]);
}
});
}
Then here is the php
include_once('connection.php');
if(isset($_POST['hello'])) {
$hello = $_POST['hello'];
$emailSearchText = mysql_real_escape_string($_POST['emailSearchText']);
$keyCardSearchText = mysql_real_escape_string($_POST['keyCardSearchText']);
$userNameSearchText = mysql_real_escape_string($_POST['userNameSearchText']);
$pinSearchText = mysql_real_escape_string($_POST['pinSearchText']);
$passwordSearchText = mysql_real_escape_string($_POST['passwordSearchText']);
$query = "SELECT * FROM Students WHERE (`User name`='$userNameSearchText' OR `Email`='$emailSearchText' OR `Key Card`='$keyCardSearchText')AND(`Password`='$passwordSearchText'OR `Pin`='$pinSearchText')";
$students = mysql_query($query);
$count = (int) mysql_num_rows($students);
$data = array();
while($student = mysql_fetch_assoc($students)) {
$data[0] = $student['First Name'];
$data[1] = $student['Last Name'];
$data[2] = $student['Date of last class'];
$data[3] = $student['Time of last class'];
$data[4] = $student['Teacher of last class'];
$data[5] = $student['Membership Type'];
$data[6] = $student['Membership Expiration Date'];
$data[7] = $student['Free Vouchers'];
$data[8] = $student['Classes Attended'];
$data[9] = $student['Classes From Pack Remaining'];
$data[10] = $student['5 Class Packs Purchased'];
$data[11] = $student['10 Class Packs Purchased'];
$data[12] = $student['Basic Memberships Purchased'];
$data[13] = $student['Unlimited Memberships Purchased'];
$data[14] = $student['Groupon Purchased'];
};
echo json_encode(array("data_db"=>$data, "msg" => "Ajax connected. The students table consist ".$count." rows data", "success" => true));
};
Your PHP script is likely producing error messages because the $_POST values you are trying to access don't match the key names you are sending in the request. For example: $_POST['emailSearchText'], yet you used emailtext in the AJAX call.
This is most likely causing jQuery to not be able to parse the response as JSON, hence the Undefined.
First of all, you have to remove the quotes or you will be passing those literals instead of the variables.
$.ajax({
...
data: {
hello: "hello",
emailtext: emailSearchText,
keycardtext: keyCardSearchText,
usernametext: userNameSearchText,
pinText: pinSearchText,
passwordtext: passwordSearchText
},
...
});
And then, like ashicus point out, in your PHP file:
$emailSearchText = mysql_real_escape_string($_POST['emailtext']);
$keyCardSearchText = mysql_real_escape_string($_POST['keycardtext']);
$userNameSearchText = mysql_real_escape_string($_POST['usernametext']);
$pinSearchText = mysql_real_escape_string($_POST['pinText']);
$passwordSearchText = mysql_real_escape_string($_POST['passwordtext']);
JS file looks ok, so this few clues to check PHP file.
See if there are even POST params there (printr all $_POST in php)
Check if your even enters IF. Add an else statement and echo some dummy json.
Check what is actually in encoded json that is echoed. Assign it to var then print.

Javascript won't post variable

Why does this code work fine in the unit test, but not in the page? I have Firebug and FirePHP in place and can see the variable pass just fine if I hard code it, the operation is passing an int just fine in the unit test, but I've tried parseInt, Math.floor, and many other wacky methods and the value for statementCount simply won't post.
The ajax:
//polling code
var statementCount = 0;
(function poll(){
setTimeout(function(){
$.ajax({ url: "RROO_update.php",
type: "POST",
data: {'meetID': 2176, 'statementCount': statementCount},
success: function(data){
if(data.length > 0){
var statements = JSON.parse(data);
//reset the statement count
statementCount = statementCount + statements.length;
$(this).actplug_RROO('formatReturns', statements, userID);
poll();
}
},
error: function(){
poll();
},
});
}, 5000);
})();
and the php:
<?php
include("../inc/variables.php");
error_reporting (E_ALL ^ E_NOTICE);
require_once('../FirePHPCore/FirePHP.class.php');
require_once('../FirePHPCore/fb.php');
$firephp = FirePHP::getInstance(true);
ob_start();
$MeetingID = $_POST['meetID'];
$StatementCount = (int)$_POST['statementCount'];
$firephp-> log($StatementCount, 'Statement count passed in' );
$Finished = FALSE;
while($Finished == FALSE){
$MeetingStats = mysql_query("SELECT RROO_UPDATE.*, MEMBER.UserName, MEMBER.UserImage FROM RROO_UPDATE JOIN MEMBER ON RROO_UPDATE.MemberID = MEMBER.MemberID WHERE MeetingID = $MeetingID ORDER BY TimeStamp DESC", $DB_Connection);
$MyNum = mysql_num_rows($MeetingStats);
$firephp->log($MyNum, 'Row Query');
if($MyNum > $StatementCount){
$Returns = array();
while($Return = mysql_fetch_array($MeetingStats)){
array_push($Returns, $Return);
}
$NewReturns = array();
$NewStats = $MyNum - $StatementCount;
$firephp->log($NewStats, 'heres the new stats count');
for($i = 0; $i < $NewStats; $i++){
array_push($NewReturns, $Returns[$i]);
}
$Here = count($NewReturns);
$firephp->log($Here, 'The length of the new returns array');
$Finished = TRUE;
echo json_encode($NewReturns);
}
else{
sleep(3);
}
}
?>
Like I said, it comes back fine on the unit test which is the same in all the aspects I can see (I actually copy pasted it into the page) the only difference being that the postback is routed differently on the page (to the plugin) but I've messed around with callback to no avail. Is there some reason the statementCount won't reset and Post in this code?
I don't think that statementCount is defined inside the callback, only in the function which executes the ajax call.
Here is a question and answer which should help you do what you want.

Categories