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
Related
I have Jquery date picker to select start date and dropdown to select number of weeks.
I'm using below codes to get the end date result but its not working:
week_number_id.on('change', function(e) {
var selectvalue = $(this).val();
//Display 'loading' status in the target select list
date_result_id.html('<i class="uk-icon-spinner uk-icon-spin"></i>');
if (selectvalue == '')
{
date_result_id.html(initial_date_result_html);
}
else
{
//Make AJAX request, using the selected value as the GET
$.ajax({
url: 'index.php',
data:'option=com_mycom&task=getmydateHTML&dvalue='+selectvalue,
success: function(output) {
date_result_id.html(output);
updateSelect(date_result_id.val());
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + ' ' + thrownError);
}
});
}
});
and on php code:
public function getmydateHTML() {
$jinput = JFactory::getApplication()->input;
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$dt = $jinput->get ('dvalue');
$choosendate = $jinput->get ('start_date');
$newdate = strtotime("+". $dt . "week", $choosendate);
echo date('M d, Y', $newdate);
exit; // this will stop Joomla processing, and not output template modules etc.
}
Result calculating date starting from jan 01, 1970, weeks are increasing correctly but the code can not get the start date
You need to convert the $choosendate to timestamp. You need to create date from your date with valid format.
See the example: https://3v4l.org/SYltO
$week = "+1 weeks"; //"+". $dt . "week"
$str = 'jan 02, 2016';//$jinput->get('start_date')
$date = date_create($str);
$choosendate = date_format($date, "m/d/Y");
$newdate = strtotime($week, strtotime($choosendate));
echo date('M d, Y', $newdate);
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
For example, I have the following data
Name Date
Aplha 10/05/1988
Bravo 10/04/1999
Charlie 10/08/1990
I'm trying to make a auto check data (database) for every minute,
and compare it with the current Date on the computer, if its the same, I can insert message like happy birthday.
Someone can provide reference or solution to this, would be appreciated.
its like notification but in this case it will send message automatic
edited note - nvm i got it..updated script
my js
$(function()
{
setInterval(function() {
$.ajax({
url: "dooBday.php",
success: function (data) {
$("#feedback").html(data);
}
});
}, 1000 * 60);
});
my dooBday function
$tgl=date("d/m");
$tglInt=date("d/m");
$tglInt=preg_replace( '~\D~', '', $tglInt);
$tglInt=intval($tglInt);
// Database Object
$tablename = "Phonebook_New";
$tablename2 = "USER_ID";
$xo=0;
$xx=0;
$VinDB = new VinDB();
// Get Data
$query2 = "SELECT * FROM ".$tablename2." WHERE UserID='".getMultiUserID()."'";
$result2 = $VinDB->query($query2);
if ($VinDB->num_rows($result2) != 0)
{
$line2 = $VinDB->fetch_array($result2);
if($line2["bdaySts"]==1 and strlen(trim($line2["bdayMsg"])) > 0){
// Get Data--------------------------------
$query = "SELECT * FROM ".$tablename." WHERE User_ID='".getMultiUserID()."' AND bdaySent='x'";
$result = $VinDB->query($query);
if ($VinDB->num_rows($result) != 0)
{
while ($line = $VinDB->fetch_array($result))
{
if(!empty($line["Ultah"])){
$tglNew=substr($line["Ultah"], 0, -5);
if($tgl==$tglNew){
$datex = date('Y/m/d');
$timex = date('H:i:s');
$schedule= date($datex . '-' . $timex);
//doo Update Contact Sent--------------------
$sqlquery[$xo]="UPDATE ".$tablename." SET bdaySent='Sent' where User_ID='".getMultiUserID()."' and nomor='".$line["nomor"]."'";
$xo++;
// doo Send Message----------------------------
$inuquery[$xx] = "INSERT INTO Schedule ";
$inuquery[$xx] .= "(message,phone_number,Schedule,Status,User_ID) ";
$inuquery[$xx] .= "VALUES ('".$line2['bdayMsg']."','".$line['PhoneNumber']."','".$schedule."','Processing','";
if (isset($_SESSION['user_id2']))
{
$inuquery[$xx] .= $_SESSION['user_id2']."')";
} else {
$inuquery[$xx] .= "Unknown')";
}
$xx++;
}}
}//end while
}// end if
}
}//end send bday
for($i=0;$i<$xo;$i++){
$result = $VinDB->query($sqlquery[$i]);
$result2 = $VinDB->query($inuquery[$i]);
}
I think you want to wish users. If I am right. You can do it like this.
put this code on your page where you would like to check every minute
setInterval(function() {
$.ajax({
url: "ajx.php",
success: function (data) {
$("#feedback").html(data);
}
});
}, 1000 * 60);
And this will be your ajax.php file
<?php
// Name Date
// Aplha 10/05/1988
// Bravo 10/04/1999
// Charlie 10/08/1990
$alphaDob = '02/04/1988';
$exp = explode('/', $alphaDob);
$userDate = $exp[0];
$userMonth = $exp[1];
$currentDate = date('Y-m-d');
$exp = explode('-', $currentDate);
$currentDate = $exp[2];
$currentMonth = $exp[1];
if($currentMonth == $userMonth && $currentDate == $userDate) {
echo 'Happy Birthday';
}
For good performance use Ajax-Long-Polling function, example can be found here Long-Polling Example
I have this jquery:
$.post('booked_dates.php', function(data) {
var bookedDays = data;
});
function isAvailable(date){
var dateAsString = date.getFullYear().toString() + "-" + (date.getMonth()+1).toString() + "-" + date.getDate();
var result = $.inArray( dateAsString, bookedDays ) ==-1 ? [true] : [false];
return result
}
$('#cal').datepicker({minDate: 0, maxDate: "+2M", beforeShowDay: isAvailable});
and this php, with date being in y-m-d form:
$merchant_date = mysql_query("SELECT date FROM merchants");
while ($result = mysql_fetch_array($merchant_date)){
$date = $result['date'];
}
I was wondering how I can store all the dates in an array, pass the array to the Jquery side, and then that would disable the "booked" dates. Basically, how can I make available an array as data and store it in bookedDays
You can json_encode() the result from MySQL in your PHP file:
$merchant_date = mysql_query("SELECT date FROM merchants");
while ($result = mysql_fetch_array($merchant_date)){
$dates[] = $result['date'];
}
echo json_encode($dates);
I am trying to create a website like penny auction how to display the count down time?
i tried that using ajax, but sometimes it swallow one or two seconds, it shows seconds like 10,9,7,6,3... i mean it doesn't show the proper count down time.. please help me to solve this problem
here is my code
<?php
#session_start();
include "includes/common.php";
include_once "includes/classes/class.Auction.php";
$objAuction = new Auction();
$result=$objAuction -> getStatus();
echo $result;
?>
//ajax code
function getStatusOne(pId)
{
var strURL="get_status_one.php?pId="+pId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
if (req.status == 200)
{
//alert(req.responseText);
var result= req.responseText.substr(1).split("|");
for (var x = 0; x < result.length; x++)
{
var resultN=result[x].split(",");
var prId=resultN[0];
var temp=resultN[1];
var sec=parseInt(temp);
var price=resultN[2];
//alert(prId+' '+temp+' '+price);
var mem=resultN[3];
var img=resultN[4];
var autobid=resultN[5];
if(img=='') {
img='images/profile/no_image.jpg'
}
if(!price)
{
price='0.00';
}
if(!mem)
{
mem='No Bidders Yet';
}
if(document.getElementById("bid_price"+prId))
{
document.getElementById("bid_price"+prId).innerHTML='$'+price;
document.getElementById("bidder_name"+prId).innerHTML=mem;
document.getElementById("userimg").src=img;
document.getElementById("bid_rate").innerHtml=autobid;
if(sec<= -1)
{
sold(prId);
if(document.getElementById('end'+pId))
{
document.getElementById('end'+pId).style.display="block";
}
if(document.getElementById('div_bid_image'))
{
document.getElementById('div_bid_image').style.display="none";
}
if(document.getElementById('clsBidB'+pId))
{
document.getElementById('clsBidB'+pId).style.display="none";
}
}
else {
if(document.getElementById('div_bid_image').style.display == "none")
{
document.getElementById('div_bid_image').style.display="block";
}
if(sec >=0)
{
SetCountdownText(sec,"div_timer"+prId,prId);
}
}
}
}
}
else
{
//alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
//php code to calculate time
function getStatus()
{
$selProd="select a.pdt_id, unix_timestamp(a.end_date) - unix_timestamp('".date('Y-m-d H:i:s')."') as seconds, b.bid_price,c.uname from tbl_products a left join tbl_auction b on a.pdt_id=b.product_id left join tbl_members c on b.member_id=c.member_id where(select unix_timestamp(a.end_date) - unix_timestamp('".date('Y-m-d H:i:s')."'))>= 0 ";
if($this->ExecuteQuery($selProd,"norows") > 0)
{
$auctionArr=$this->ExecuteQuery($selProd,"select");
$auctionName=$this->array2str($auctionArr);
}
return $auctionName;
}
function array2str($array,$level=1)
{
$str = array();
foreach($array as $key=>$value) {
if(is_int($key))
{
$nkey = $key;
$nvalue = is_array($value)?'|'.$this->array2str( $value ) : $value;
$str[] = $nvalue;
}
}
return implode(',',$str);
}
try this
<?php
$target = mktime(0, 0, 0, 14, 07, 2011) ;
$today = time () ;
$difference =($target-$today) ;
$days =(int) ($difference/86400) ;
print "Our event will occur in $days days";
?>
Assuming you have something like a DIV with the ID "countdown" (to display the countdown in):
Example JavaScript (assumes use of jQuery - recommended):
(function(jQuery) {
updateCountdown("countdown"); // Call on page load
var countdown = setInterval('updateCountdown("countdown")', 1000); // Update countdown every second
})(jQuery);
function updateCountdown(elementId) {
jQuery.ajax({
url: "/ajax/countdown.php?auctionId=123",
type: "GET",
dataType: "json",
success: function(response) {
// Insert value into target element
jQuery("#"+elementId).html(response["timeRemaining"]);
// Stop countdown when complete
if (response["countdownComplete"] == true)
clearInterval(countdown);
}
});
}
Example PHP script (assumed to be at /ajax/countdown.php by the above JavaScript):
<? php
/* Insert your own logic here */
$response["timeRemaining"] = "5 seconds";
$response["countdownComplete"] = false; // Set to true when countdown complete
echo json_encode(response);
?>
I'd recommend doing all the calculation server side (in PHP) as it has really excellent time/date handling (with lots of built in methods) and requires less code to implement overall.
Have a PHP page echo out the countdown time. And then use something like jQuery's AJAX HTTP Request for that page and populate the response in a DOM element somewhere.
Why do you need Ajax to display the countdown time? Why can't you just display it when the page loads along with the rest of the data?