Retrieving and Comparing Dates using JQuery And PHP - php

I am using jQuery's datepicker in wordpress/PHP and I am using this code to show dates:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function() {
$("#datepicker").datepicker();
$("#datepicker").datepicker("option","dateFormat",'yy-mm-dd');
});
</script>
Date<input type="text" id="datepicker" size="20" maxlength="15" style="width: 80px;" readonly="readonly"/>
It successfully displays my date.
Also, I have a table (wp_redeem_vouchers) in the database that has specific voucher redemption dates saved in it:
id wp_deal_id redeem_date
1 Amazon6767 2012-03-21
2 Ebay87nm 2013-06-12
3 M&Svouc 2013-01-01
4 ASDA 2011-09-08
Question:
How can I retrieve "redeem_date" and compare with the datepicker's textbox date (upon selection) with the date already saved in the database?
Is there anyway I could disable past date so that user can't choose the past date from date picker? i.e The user on 14/03/2013 can't choose 22/02/2013 from datepicker.

For your i)
$('#datepicker').datepicker( {
minDate: 0,
onSelect: function(dateText, inst) {
$.ajax({
type: "POST",
url: "some.php",
data: { date: dateText },
onSuccess: function(e){
alert("success");
}
});
});
Then in the some.php file you do your compare with mysql and you return a success or failure getting the alert(success).
Then I would start with
$date = $_POST['date'];
die($date);
In the some.php just to see if it is passed correctly.

Well, you can pass your datepicker date string (adjust format to $("#datepicker").datepicker("option","dateFormat",'yyyy-mm-dd');) to following JavaScript function which creates a Date object:
function createDate(s) {
var bits = s.split('-');
var d = new Date(bits[0], bits[1] - 1, bits[2]);
return d;
}
Then you have to retrieve the date value from your database.
I do not know if there is a wordpress limitation but you can trigger a Ajax-Request which reads out the database value and give you as a response the date string as a JavaScript variable.
This variable can also be passed to the createDate(date) function. With these two date objects you can call easily compare the date with the time in milliseconds -> getTime() function of date object.
Regards

Related

php how to post date range picker with 2 variables

I'm using date range picker
<input class="form-control input-daterange-datepicker" type="text" name="daterange" value="01/01/2015 - 31/01/2015" />
When I post the form i get 1 value for this range.
is it possible to get 2 values - from and till (when i post)?
<!-- Date range Plugin JavaScript -->
<script src="vendors/bootstrap-daterangepicker/daterangepicker.js"></script>
<script>
// Daterange picker
$('.input-daterange-datepicker').daterangepicker({
buttonClasses: ['btn', 'btn-sm'],
format: 'DD/MM/YYYY',
minDate: '06/01/2015',
maxDate: '06/30/2025',
applyClass: 'btn-danger',
cancelClass: 'btn-inverse',
dateLimit: {
days: 45
}
});
</script>
I think that this is the right project -
https://github.com/dangrossman/daterangepicker
The widget will post both the dates as one string. Since you named your input daterange you can access the result in PHP using:
$aRanges = explode(' - ', $_POST['daterange']);
var_dump($aRanges);

I have a jQuery date that I am passiving via ajax to a php script then using the date in an sql insert into mysql database

I have a javascript date that I am passing via ajax to a php script then using the date in an sql insert into mysql database. I can't figure out how to format the date so the SQL call accepts it. Can anyone help with this?
In the AJAX call I've tried passing the date object as is, converting to JSON, to UTC.
The error I get is:
Incorrect date value: 'Thu, 01 May 1902 03:01:00 GMT' for column 'uspr_dob'
This all works if I remove the date line from the SQL code. ie I update the other fields but not the date. So everything else is working except the date passing.
jQuery date formation:
var dob = new Date(year, month, day, hours, minutes, 0, 0);
jQuery AJAX call:
var save_result = jQuery.ajax({
url: lb_path + "update_user.php",
data: { 'lb_user_id' : this.id,
'lb_dob' : this.dob.toUTCString(), //toJSON
... },
type: 'POST',
datatype: 'json',
success: function(data, status) {
...
}, // End success
error: function (xhr, ajaxOptions, thrownError) {
...
}
}); // End load the supplement list
PHP code is:
$sql = "UPDATE userpref
SET uspr_person_group = \"".$lb_gender."\",
uspr_diet_type = (SELECT diet_id FROM diet WHERE diet_name = \"".$lb_diet."\"),
uspr_exercise_profile = (SELECT exprof_id FROM exercise_profile WHERE exprof_name = \"".$lb_exercise."\"),
uspr_dob = \"".$lb_dob."\"
WHERE uspr_user_id = ".$lb_user_id;
If you use YYYY-MM-dd format you will never run into any issues. It is better to convert it before passing it to the server in your case.
Please refer to Get String in YYYYMMDD format from JS date object? .
OK - I found the problem - The database documentation showed the field in the table was DATETIME ... when actually it was DATE.
Once I spotted that and massaged the datetime string into MySQL's format it all worked beautifully!
Still I would think that there is an easier way to do this ... ie a date format in javascript that can be passed straight through AJAX, PHP then SQL and work without any formatting.

Date field is being reset in PHP and MySQL

When I am trying to edit some fields in the form, the date is being reset to 01-01-1970 01:00:00 but its stores and retrieves its value from the database perfectly for the very first time. Then it's being reset when I edit some other fields except date.
Below my jQuery date picker:
<script>
$(document).ready(function(){
$("#policy_start_date").datepicker({
numberOfMonths: 1,
onSelect: function(selected) {
$("#policy_end_date").datepicker("option","minDate", selected)
}
});
$("#policy_end_date").datepicker({
numberOfMonths: 1,
onSelect: function(selected) {
$("#policy_start_date").datepicker("option","maxDate", selected)
}
});
});
</script>
POST DATA
$date_t=$_POST['policy_start_date'];
$datearr=explode('/',$date_t);
$month=$datearr[0];
$day=$datearr[1];
$year=$datearr[2];
$policy_start_date=$year."-".$month."-".$day;
//$policy_end_date = $_POST['policy_end_date'];
$date_t=$_POST['policy_end_date'];
$datearr=explode('/',$date_t);
$month=$datearr[0];
$day=$datearr[1];
$year=$datearr[2];
$policy_end_date=$year."-".$month."-".$day;
Usually this is happen because the format stored in db and the format sent/acceptable by datepicker.
Standard datepicker format is 09/03/2013 (m/d/y).
What is displayed on the textbox when you echoed the data?
1. 09/03/2013 (m/d/y)
or
2. 2013-09-13 00:00:00 (Y-m-d H:i:s)
if option one (1) is displayed, then we certain need to see the code that display the form you used.
if option two(2) is displayed, then you need to format it before echoing into the textbox.
use this,
$time = strtotime($date_stored_in_database);
$your_date = date('Y/m/d',$time);
The strtotime will convert the date you stored in database into UNIX TIMESTAMP, and date function will convert it to the format you needed.

JQuery and PHP Date difference

I am using a jquery date picker and also setting a date through php date('Y-m-D') functions. Both of them give different date for today. Jquery picker fills the field with the date that is one day ahead of php date(). Here is the function for jquery. I need jquery to show same date for today as php.
<script type="text/javascript" charset="utf-8">
var $j = jQuery.noConflict();
$j(function()
{
// initialise the "Select date" link
$j('#date-pick')
.datePicker(
// associate the link with a date picker
{
createButton:false,
startDate: '01/01/1970',
endDate: (new Date()).asString()
//endDate:<?php echo date('y-m-d'); ?>
}
).bind(
// when the link is clicked display the date picker
'click',
function()
{
updateSelects($j(this).dpGetSelected()[0]);
$j(this).dpDisplay();
return false;
}
).bind(
// when a date is selected update the SELECTs
'dateSelected',
function(e, selectedDate, $td, state)
{
updateSelects(selectedDate);
}
).bind(
'dpClosed',
function(e, selected)
{
updateSelects(selected[0]);
}
).val(new Date().asString()).trigger('change');
var updateSelects = function (selectedDate)
{
var selectedDate = new Date(selectedDate);
if(selectedDate != "Invalid Date")
{
$j('#d').val(selectedDate.getDate());
$j('#m').val(selectedDate.getMonth()+1);
$j('#y').val(selectedDate.getFullYear());
}
}
// listen for when the selects are changed and update the picker
// default the position of the selects to today
var today = new Date();
updateSelects(today.getTime());
});
</script>
jQuery uses the client computer's date while php uses the server's date. They're basically different if you haven't set the default timezone in php. Take a look at this:
http://php.net/manual/en/function.date-default-timezone-set.php
You can set the default timezone in php.ini file located on the PHP main directory (Eg. PHP5.4)
As for the using of the server's date in the datepicker:
A quick google search lead me to this: how to display server side dates in jquery datepicker?
basically what they have done is creating a new date based on the current timestamp:
$timestamp = strtotime("2012-08-02");
minDate: new Date('<?php echo $timestamp; ?>');
DO NOT TRUST THE CLIENTS DATE AND TIME
These values can be altered at a whim.
Just use them on advisement.
Besides Javascript is there to enhance the users experience (i.e. make it more interactive). But at the end of the day you will have to pick up the pieces it you do not validate and verify the data you get from the client

JQuery Datepickers to POST

I have asked this before, but my meaning was not understtod...
My Situation is that I need the Start and End JQuery datepicker on the webpage, and it must... #1 - The End Date must always be greater then Start Date... #2 - The date range must POST data from MySQL to create a table of the data on the webpage.
How can I change the script below (that has #1 working of the tasks needed above), to also POST the information from MySQL via PHP back to the HTML DIV.
See the example of what I am building on my webpage here
1.<script type="text/javascript">
$(function () {
var start1 = $('#start1');
var end1 = $('#end1');
start1.datepicker({ onClose: clearEndDate });
end1.datepicker({ beforeShow: setMinDateForEndDate });
function setMinDateForEndDate() {
var d = start1.datepicker('getDate');
if (d) return { minDate: d }
}
function clearEndDate(dateText, inst) {
end1.val('');
}
})
There was another jQuery function on your site that you didn't include:
$('#button').click(function() {
$.post('report.php', {
start: $('#start1').val(),
end: $('#end1').val()
},
function(data) {
$('#genreport').html(data).show();
});
});
You probably already know this, but you will also need to reformat and filter/verify the date inputs in your report.php page. I hope this helps. I didn't realize this question was so old until I just posted it. HAH! Just ignore this, as you probably have it working already.

Categories