i have a script. jQuery datepicker with url's on database.
<script>
$(function() {
$('#datepicker').datepicker({
beforeShowDay: daysToMark,
onSelect: function(date,evt){
if (evt.currentMonth < 10){
evt.currentMonth = "0"+evt.currentMonth;
}
if (evt.currentDay < 10){
evt.currentDay = "0"+evt.currentDay;
}
daysToMark(evt.currentYear+"-"+evt.currentMonth+"-"+evt.currentDay);
date.dpDiv.find('.ui-datepicker-current-day a')
.css('background-color', '#000000');
}
});
});
<?
$dateArray = array();
$sql = mysql_query("SELECT *
FROM module_news
");
while ($row = mysql_fetch_array($sql)) {
array_push($dateArray,$row["tarigi"]);
}
?>
var js_array = new Array();
js_array = <?=json_encode($dateArray);?>;
var dates = js_array;
function daysToMark(evt) {
if($.inArray(evt, js_array) != -1 )
{
window.open("index.php?action=news_archive&date="+evt+"&lang=<?=$lang?>", "_self");
}
return [true, "", ""];
}
</script>
I have database date links in array, and i want to highlight links, so when i write news at 2011-07-08 on my calendar it 'll be linked but not highlighted, how can i change background color of linked dates?
thanks
In the daysToMark method you return return [true, "", ""]; as required by the beforeShowDay event.
The second position in that array hold a class that will be applied to the data. So if you add a class there return [true, "linked", ""]; and in you css code set a rule of
.linked .ui-state-default{
background-color:red;
background-image:none; /*this in case the them you use uses background images*/
}
it should do what you want..
demo at http://jsfiddle.net/gaby/S79fa/
replace this line
date.dpDiv.find('.ui-datepicker-current-day a')
.css('background-color', '#000000');
with below code
var atag = date.dpDiv.find('.ui-datepicker-current-day a');
atag.queue(function() {
atag.css("background-color", "black");
});
this may be helpful
Thanks.
Related
<?php
$sql = "SELECT * FROM expense WHERE userid = $userid";
$expense_date= array(); //array declared to be used below
$amount = array();// array declared
$result = mysqli_query($conn, $sql);
if(!$result){
die("query failed"); // query failed due to no connection or error in query
} else {
while( $row = mysqli_fetch_assoc($result)){ // fetches infromation
array_push($amount, $row["amount"]); //pushes my distances whic are returned from the query from the database into an array
$date_entered = ( date("d-n-y", strtotime($row["timestamp"])));
array_push($expense_date, $date_entered);//pushes date travelled
}
}
//$arr = array('distance'=>$dist_covered, 'dateTravel'=>$travel_date);
//print_r(json_encode($arr)); ------ make sure distance are being inserted into the database
echo $date_entered; ?>
<script type="text/javascript">
var unavailableDates = <?php print_r(json_encode($date_entered))?>;
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
}
else {
return [false, "", "Unavailable"];
}
}
$(function() {
$( "#Datepicker1" ).datepicker({
numberOfMonths:2,
beforeShowDay: unavailable
});
});
</script>
I am trying to get the unavailableDates variable to pick out a date from the database. the variable which is in php is echoing out the date in the same format. but the variable is not recognizing it. If i enter the dates manually it works.
var unavailableDates = <?php echo json_encode($date_entered)); ?> || '';
Both print_r() and var_dump() are used to display data for debugging purposes. print and echo are used for outputting strings. Using echo is most common.
$d = date("d-n-y");
print_r($d);
var_dump($d);
echo $d;
Will produce:
11-2-16
string(7) "11-2-16"
11-2-16
So, even though you're using print_r() instead of echo, the result is the same output. This is because it's a string variable in this case. Or is this an array of dates?
You may have another issue in your code. Are you getting any console errors?
I may be missing something. Is unavailableDates supposed to be an array of dates? In that case, you might have your variables mixed up a bit. See the array_push() PHP function.
See
http://php.net/manual/en/function.array-push.php
array_push($expenseDates, $date_entered);//pushes date traveled
Then...
var unavailableDates = <?php echo (!empty($expenseDates)) ? json_encode($expenseDates) || []; ?>;
Right, your code here is a bit of a mess to be honest, lots of obvious issues which I have corrected below:
<?php
$sql = "SELECT * FROM expense WHERE userid = $userid";
$expense_date = array(); //array declared to be used below
$amount = array(); // array declared
$result = mysqli_query($conn, $sql);
if (!$result) {
die("query failed"); // query failed due to no connection or error in query
} else {
while ($row = mysqli_fetch_assoc($result)) {
$amount[] = $row["amount"];
$date_entered = date("d-m-y", $row["timestamp"]); #CORRECTED - ONLY FEED IN THE TIMESTAMP
$expense_date[] = $date_entered;
}
}
//echo $date_entered; #WHY IS THIS BEING ECHOED OUT HERE FROM PHP?
?>
<script type="text/javascript">
var unavailableDates = '<?= $date_entered ?>';
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
}
else {
return [false, "", "Unavailable"];
}
}
$(function () {
$("#Datepicker1").datepicker({
numberOfMonths: 2,
//beforeShowDay: unavailable # WHAT IS THIS?
beforeShowDay: unavailable('MISSING_DATE')
});
});
</script>
Is this all happening in 1 .php file?
Look in the datepicker code - looks like that is meant to be a call to the unavailable() .js function? What date is that meant to call?
I am using the below code to create a YUI datatable with dynamic data(columns). But am facing a issue in server side pagination. As of now it is working fine with client side pagination, but I need server side pagination, so that my page loading time will get reduced. Can you help me on this to fix the issue. Since I'm struggling in this area for past 2 days.Server side pagination with AJAX to render the data is my expectation.
Here is the code I Used
DataProvider.prototype = {
url:null,
data:null,
ds:null,
getData:function() {return this.data},
initialize:function(){
var str = generateRequest();
var newUrl = this.url+str;
YAHOO.util.Connect.asyncRequest('GET', newUrl, this);
},
success:function(response){
var responseVal = YAHOO.lang.JSON.parse(response.responseText);
var columnList = responseVal.columnList;
var sortedBy = responseVal.sortedBy;
this.data = responseVal.results;
if(this.data == '') {
$('#dynamicdata').html('<font style="color:red;"> No Data Found!</font>');
} else {
this.ds = new YAHOO.util.FunctionDataSource(function(){return this.dataProvider.getData()});
this.ds.responseSchema = {
resultsList:"results",
fields:columnList,
// Access to values in the server response
metaFields: {
totalRecords: "totalRecords",
startIndex: "startIndex"
}
}
this.ds.dataProvider = this;
// DataTable configuration
var myConfigs = {
paginator: new YAHOO.widget.Paginator({ rowsPerPage:20 }), // Enables pagination
width:"80%", height:"auto"
};
// FORMATTING CELL COLOUR BASED ON THEIR VALUES
var myCustomFormatter = function(elLiner, oRecord, oColumn, oData) {
var columnKey = oColumn.getKey();
var frmCurrentPeroid = $('#from').val();
//var frmCurrentPeroid = '2013-03-13';
var defaultLabels = ['Product type','Total 1','Total 2','Change'];
if (isDate(columnKey) && $.inArray(columnKey, defaultLabels) === -1) {
if(columnKey < frmCurrentPeroid) {
YAHOO.util.Dom.addClass(elLiner.parentNode,'orange');
elLiner.innerHTML = oData;
//alert('blue');
} else {
YAHOO.util.Dom.addClass(elLiner.parentNode,'blue');
elLiner.innerHTML = oData;
}
} else {
if(columnKey == 'Total 1') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'orange');
elLiner.innerHTML = oData;
//alert('blue');
}
else if(columnKey == 'Total 2') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'blue');
elLiner.innerHTML = oData;
//alert('blue');
}
else if(columnKey == 'Change') {
split_data = oData.toString().split('_');
var fieldData = null;
var fieldFormatter = null;
fieldData = split_data[0];
fieldFormatter = split_data[1];
if(fieldFormatter == 'green') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'green');
elLiner.innerHTML = fieldData;
}
if(fieldFormatter == 'red') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'red');
elLiner.innerHTML = fieldData;
}
}
else if(columnKey == 'Product Name') {
var filterStr = oData.substring(0,30);
elLiner.innerHTML = ''+filterStr+'';
//alert('blue');
}
else {
elLiner.innerHTML = oData;
}
}
};
// Add the custom formatter to the shortcuts
YAHOO.widget.DataTable.Formatter.myCustom = myCustomFormatter;
//YAHOO.widget.DataTable.formatLink = formatLink;
/* make call to initialize your table using the data set */
var myDataTable = new YAHOO.widget.DataTable("dynamicdata", columnList, this.ds, myConfigs);
}
}
}
Followed the code posted in this page
Click here
Thanks in Advance,
Raja
I haven't been doing YUI2 for quite some time so I am no longer able to help you directly. Perhaps this example can help: http://www.satyam.com.ar/yui/#ServerDriven . I do remember that there were big changes in 2.6 and this examples are marked 2.4, perhaps they no longer work.
In the following example, I need to know how to call, via json, a php script that reads a MySql table, and return the array with the $myBadDates to be disable:
$(function() {
$( "#pickdate" ).datepicker({
dateFormat: 'dd MM yy',
beforeShowDay: checkAvailability
});
})
var $myBadDates = new Array("10 October 2010","21 October 2010","12 November 2010");
function checkAvailability(mydate){
var $return=true;
var $returnclass ="available";
$checkdate = $.datepicker.formatDate('dd MM yy', mydate);
for(var i = 0; i < $myBadDates.length; i++)
{
if($myBadDates[i] == $checkdate)
{
$return = false;
$returnclass= "unavailable";
}
}
return [$return,$returnclass];
}
Here is my php script : close_dates.php, how do I send the json ajax request and get the array result into the checkAvailability Function : >
include 'panel/db.php';
$dates_closed = array();
/// Query Dates Closed ///
$query = "SELECT dates from closed_dates order by dates ";
$result = mysql_query($query);
while($row=mysql_fetch_array($result)) {
$days = $row['dates'];
array_push($date_closed,$days);
}
echo json_encode($date_closed);
?>
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?
I have code:
$(function() {
$('#datepicker').datepicker({
beforeShowDay: daysToMarkAndLink
});
});
function daysToMarkAndLink(date) {
.....(if daysToMarkAndLink matches){
......(link goes here and also highlight);
}
return [false];
}
<?
$sql = mysql_query("SELECT * FROM news");
while ($row = mysql_fetch_array($sql))
{
print $row["time_added"];
}
?>
i want to do something like, highlight the only days i have in database also and link them on my news page, filter by date_added.
i want a very simple news calendar on jQuery datepicker.
thanks
To implement this, you need to use a mix of beforeShowDay and onSelect like this:
<input type="textbox" id="mydate"></input>
<script>
//<![CDATA[
var dateArray = new Array();
// generate these from mysql. Replace the date by your date field
dateArray.push({date: new Date('2011/7/5'), link: 'http://mylink1.com'});
dateArray.push({date: new Date('2011/7/6'), link: 'http://mylink2.com'});
dateArray.push({date: new Date('2011/7/10'), link: 'http://mylink3.com'});
dateArray.push({date: new Date('2011/7/15'), link: 'http://mylink4.com'});
function formatDate(date) // we use function to convert date to a string we can debug
{
var mon = date.getMonth(); // 0-based
var day = date.getDate(); // 1-based
var yyy = date.getFullYear();
return (mon+1)+'/'+day+'/'+yyy;
}
$(function(){
$("#mydate").datepicker({
beforeShowDay: function(date) {
var bFound = false;
var sDate = formatDate(date);
for (var i = 0; i < dateArray.length; i++) {
var compDate = formatDate(dateArray[i].date);
if (sDate == compDate) {
bFound = true;
break;
}
}
return [bFound,'',''];
},
onSelect: function(dateText, inst) {
var sDate = formatDate(new Date(dateText));
for (var i = 0; i < dateArray.length; i++) {
var compDate = formatDate(dateArray[i].date);
if (sDate == compDate) {
document.location.href = dateArray[i].link;
break;
}
}
}
});
});
//]]>
</script>