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.
Related
I've set setInterval to update my scheduler. I'm getting data from server in JSON format. But Scheduler is not getting update if I used json data, But if I put static values it works fine. Following is my code.
// It doesn't work
setInterval(function() {
$.post('ajax_comet.php',{sectionIds:sectionIds},function (data){
if(data.processing.length>0)
{
for(var i=0;i<data.processing.length;i++)
{
var startdt=data.processing[i].start_interval.split(",");
var endt=data.processing[i].end_interval.split(",");
var month=parseInt(startdt[1])-1;
var start=startdt[0]+","+month+","+startdt[2]+","+startdt[3]+","+startdt[4];
var end=endt[0]+","+month+","+endt[2]+","+endt[3]+","+endt[4];
var section="'"+data.processing[i].section_id+"'";
console.log(start);
console.log(end);
scheduler.addMarkedTimespan({
start_date: new Date(start),
end_date: new Date(end),
css: "inprocess",
sections: {
unit: section
}
});
scheduler.updateView();
}
Same TimeInterval with static data works fine.
// This works properly.
setInterval(function() {
$.post('ajax_comet.php',{sectionIds:sectionIds},function (data){
if(data.processing.length>0)
{
for(var i=0;i<data.processing.length;i++)
{
var startdt=data.processing[i].start_interval.split(",");
var endt=data.processing[i].end_interval.split(",");
var month=parseInt(startdt[1])-1;
var start=startdt[0]+","+month+","+startdt[2]+","+startdt[3]+","+startdt[4];
var end=endt[0]+","+month+","+endt[2]+","+endt[3]+","+endt[4];
var section="'"+data.processing[i].section_id+"'";
console.log(start);
console.log(end);
scheduler.addMarkedTimespan({
start_date: new Date(2013,11,29,01,00),
end_date: new Date(2013,11,29,01,30),
css: "inprocess",
sections: {
unit: 'a7b6e635-f62f-6f12-020f-52a959d1ca47'
}
});
scheduler.updateView();
}
}
},'json');
}, 5000);
}
},'json');
}, 5000);
If it works with the static data, that means that dynamic data either comes wrong or is parsed wrong on the client.
Make sure that dates and section are correct.
For example, in this code, where you collect a date string from the ajax values and check this string in console:
var start=startdt[0]+","+month+","+startdt[2]+","+startdt[3]+","+startdt[4];
var end=endt[0]+","+month+","+endt[2]+","+endt[3]+","+endt[4];
console.log(start);
console.log(end);
It would be more informative if you check the resulting date, that is passed to the scheduler API.
console.log(new Date(start));
console.log(new Date(end));
Date string might have some non-obvious error which results in invalid date object.
Secondly, the code that collects the dates is rather complex. I'd suggest to use a simplier format for transfering dates from the server(for example use unix timestamp), or to define some helper function for parsing them.
FYI, scheduler library includes scheduler.date object that defines methods for working with dates.
So you can define parse function like following. That leaves much less space for typos and accidental errors. Not quite sure that I've specified the correct date format, but you can change it if it's necessary
var parseDate = scheduler.date.str_to_date("%Y, %m, %d, %H, %i");
var start = parseDate(data.processing[i].start_interval),
end = parseDate(data.processing[i].end_interval);
One particularly suspicious line is where you retreive id of the section:
var section="'"+data.processing[i].section_id+"'";
I think you add extra quotes to the section id here. I mean var section will be equal to
"'a7b6e635-f62f-6f12-020f-52a959d1ca47'" , while in your static code you use "a7b6e635-f62f-6f12-020f-52a959d1ca47" - without extra quotes
One more thing. You call scheduler.updateView() each time timespan is added. Since this command triggers complete redraw of the calendar, it's better to call it only once when the loop is finished.
UPDATE:
here is the code sample. Didn't actually run it, but i hope it clarifies the text above
setInterval(function() {
var parseDate = scheduler.date.str_to_date("%Y, %m, %d, %H, %i");// parse string of specified format into date object
$.post('ajax_comet.php',{sectionIds:sectionIds},function (data){
if(data.processing.length>0)
{
for(var i=0;i<data.processing.length;i++)
{
var timespan = data.processing[i];
var start = parseDate(timespan.start_interval),
end = parseDate(timespan.end_interval),
section = timespan.section_id;
console.log(start);
console.log(end);
scheduler.addMarkedTimespan({
start_date: start,
end_date: end,
css: "inprocess",
sections: {
unit: section
}
});
}
//update calendar after loop is finished
scheduler.updateView();
}
},'json');
}, 5000);
I have added some code to my website but just can't fiqure out how to add cookie functionality
This is the code so far:
<script type="text/javascript">
$(document).ready(function () {
$.fancybox('<p class="msgAlert">The following pictures contain nudity. <br />If you are not allowed or willing to watch such content please leave this page.<p>Yes I Accept</p></p>', {
closeBtn: false,
closeClick: false,
helpers: {
overlay: {
css: {
'background': 'rgba(0, 0, 0, 0.9)'
}
}
}
});
$("body").on("click", "#do_accept", function () {
$.fancybox.close();
});
$("body").on("click", ".fancybox-overlay", function () {
window.location.href = "index.php";
});
});
</script>
I can't add php code so I need some advice. The idea ist to have a 10 day cookie in order to show the message just once every 10 days.
Here's the link: https://www.olafernst.com/photo/gallerynudes.html
Thanks a lot
To set cookies in javascript just use document.cookie
document.cookie = "Name=Value; expires=<DATE>';
to get date in right format you can use toUTCString method on Date object.
To add days to current date you can use answer to this quetion:
How to add number of days to today's date?
You use jquery so you can use jQuery cookie plugin for this as #gustavogb write in a comment.
I'm using fullcalendar to present events of my site members. Everyone can add own event. Each event have to have unique ID which I'm getting using SELECT INCREMENT(MAX('id')) in PHP. Then proper var is passed to JavaScript and here is a problem. The number is given to the fullcalendar renderEvent function at the second try of adding new event. At first click on calendar, variable is empty as declared (in variable named newEventId).
Here is my code:
function showCalendar() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var newEventId = '';
$('#kalendarz').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month'
},
editable: false,
dayClick: function(e)
{
$.getJSON('/ajax/call/bands/AddEvent', function(data) {
newEventId = data.dane;
});
console.log(newEventId); // <- empty, then with ID at second click...
$("#kalendarz").fullCalendar('renderEvent',
{
title: 'Termin zajęty',
start: e,
id: newEventId
});
},
});
}
What is the problem? renderEvent function is not waiting for getJSON to finish job? Could I fix it?
$.getJSON is AJAX, AJAX is asynchronous! Set it inside $.getJSON callback function:
$.getJSON('/ajax/call/bands/AddEvent', function (data) {
newEventId = data.dane;
$("#kalendarz").fullCalendar('renderEvent', {
title: 'Termin zajęty',
start: e,
id: newEventId
});
});
getJson() initiates an AJAX request, which is asynchronous, getJSON returns after initiating the AJAX-request, but that doesn´t mean that the request itself has finished already. Therefore you can hand over a function onSuccess, which will be called with the received data when the request finished.
If the mechanism wouldn´t work this way you weren´t able to do anything while the request is sent - imagine clicking somewhere, that click calls a function and somehow a request is started, then everything would wait until the request would finish: at the highest level you couldn´t even move your mouse anymore until you receive some response data - that isn´t user-friendly at all ;)
Solving your problem is easy by putting all the code after your request which depends on its response inside the onSuccess-function (you have the function already)
Background Info
I'm fiddling around with some PHP and AJAX at the moment, to try and get the code working for an auto refreshing div (every 10 seconds), that contains comments.
Here is javascript code I am using to refresh the div..
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#content_main').load('/feed_main.php');
}, 5000);
});
// ]]></script>
The code that will populate the div called "content_main", which is in feed_main.php, essentially accesses the database and echo's out the latest comments ...
Question
Is it possible, to only load the div "content_main" if the data inside of it, hasn't changed since the last time it was loaded?
My logic
Because I'm relatively new to javascript and AJAX I don't quite know how to do this, but my logic is:
For the first time it is run..
load data from feed_main.php file
Create a unique value (perhaps a hash value? ) to identify say 3 unique comments
Every other time it is run...
load the data from feed_main.php file
create a NEW unique value
check this value with the previous one
if they're the same, don't refresh the div, just leave things as they are, but if they're different then refresh..
The reason why I want to do this is because the comments usually have pictures attached, and it is quite annoying to see the image reload every time.
Any help with this would be greatly appreciated.
I've faced similar problem not too long ago, i assume that you using mysql or something for your comments storage serverside ?
I solved my problem by first adding timestamp integer column to my mysql table, then when i added a new row, i'd just simply use time() to save the current time.
mysql row insert example:
$query = "INSERT INTO comments (name, text, timestamp) VALUES ('". $name ."', '". $text ."',". time() .");";
step two would be to json_encode the data you sending from serverside:
$output = array();
if ($html && $html !== '') { // do we have any script output ?
$output['payload'] = $html; // your current script output would go in this variable
}
$output['time'] = time(); // so we know when did we last check for payload update
$json = json_encode($output, ((int)JSON_NUMERIC_CHECK)); // jsonify the array
echo $json; // send it to the client
So, now instead of pure html, your serverside script returns something like this:
{
"payload":"<div class=\"name\">Derpin<\/div><div class=\"msg\">Foo Bar!<\/div>",
"time":1354167493
}
You can grab the data in javascript simply enough:
<script type="text/javascript"> // <![CDATA[
var lastcheck;
var content_main = $('#content_main');
pollTimer = setInterval(function() {
updateJson();
}, 10000);
function updateJson() {
var request = '/feed_main.php?timestamp='+ (lastcheck ? lastcheck : 0);
$.ajax({
url: request,
dataType: 'json',
async: false,
cache: false,
success: function(result) {
if (result.payload) { // new data
lastcheck = result.time; // update stored timestamp
content_main.html(result.payload + content_main.html()); // update html element
} else { // no new data, update only timestamp
lastcheck = result.time;
}
}
});
}
// ]]> </script>
that pretty much takes care of communication between server and client, now you just query your database something like this:
$timestamp = 0;
$where = '';
if (isset($_GET['timestamp'])) {
$timestamp = your_arg_sanitizer($_GET['timestamp']);
}
if ($timestamp) {
$where = ' WHERE timestamp >= '.$timestamp;
}
$query = 'SELECT * FROM comments'. $where .' ORDER BY timestamp DESC;';
The timestamps get passed back and forth, client always sending the timestamp returned by the server in previous query.
Your server only sends comments that were submitted since you checked last time, and you can prepend them to the end of the html like i did. (warning: i have not added any kind of sanity control to that, your comments could get extremely long)
Since you poll for new data every 10 seconds you might want to consider sending pure data across the ajax call to save substantial chunk bandwidth (json string with just timestamp in it, is only around 20 bytes).
You can then use javascript to generate the html, it also has the advantage of offloading lot of the work from your server to the client :). You will also get much finer control over how many comments you want to display at once.
I've made some fairly large assumptions, you will have to modify the code to suit your needs. If you use my code, and your cat|computer|house happens to explode, you get to keep all the pieces :)
How about this:
<script type="text/javascript">
// <![CDATA[
$(function () {
function reload (elem, interval) {
var $elem = $(elem);
// grab the original html
var $original = $elem.html();
$.ajax({
cache : false,
url : '/feed_main.php',
type : 'get',
success : function (data) {
// compare the result to the original
if ($original == data) {
// just start the timer if the data is the same
setTimeout(function () {
reload(elem, interval)
}, interval);
return;
}
// or update the html with new data
$elem.html(data);
// and start the timer
setTimeout(function () {
reload(elem, interval)
}, interval);
}
});
}
// call it the first time
reload('#content_main', 10000);
});
// ]]>
</script>
This is just an idea to get you going it doesn't deal with errors or timeouts.
Best And Easy Code
setInterval(function()
{
$.ajax({
type:"post",
url:"uourpage.php",
datatype:"html",
success:function(data)
{
$("#div").html(data);
}
});
}, 5000);//time in milliseconds
I have got site with dynamic refreshing divs.
Source:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script>
var auto_refresh = setInterval(
function()
{
$('#loaddiv').fadeOut('slow').load('boo.php').fadeIn("slow");
$('#loaddiv2').fadeOut('slow').load('boo2.php').fadeIn("slow");
}, 1000);
</script>
But I want fadeout and fadein only if boo.php return different(updated) value than actuall div. How compare new and actuall value and do this?
P.s Sorry for bad English but I'm Polish
You'll need to write a callback function that inspects the returned data and compares it to what's stored within the div already. Additionally, the functions that show/reveal the div will probably need to be moved to the callback function as well.
Documentation is available here.
You'd have to write an Ajax function to boo.php and compare the result with the div's value
$.ajax(
{
url: "boo.php",
success: function(result)
{
if($("#loaddiv").html() != result)
{
$("#loaddiv").fadeOut("slow")
$("#loaddiv").html(result);
$("#loaddiv").fadeIn("slow");
}
}
});
You need to check the result you are getting from the ajax call and compare it with the current content. Assuming you have an element with ID MsgCount in your Ajax response and current Div Markup and you are using the value of that to compare, the below code will work
$(function() {
var auto_refresh = setInterval(function(){
var currentMsgCount= $('#MsgCount').text();
$.get("boo.php",function(data){
var resultData=$(data);
var newMsgCount= resultData.filter('#MsgCount').text();
if(newMsgCount!=currentMsgCount)
{
//content is different. Let's show it
$('#loaddiv').fadeOut('slow',function(){
$('#loaddiv').html(data).fadeIn("slow");
});
}
});
}, 1000);
});