Dhtmlx Scheduler is not being update in TimeInterval - php

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);

Related

Retrieve data from PHP file by ajax

I found a script on the net, which makes two PHP files interact.
Specifically, the first file (details.php) shows some statistical data of a football match. If the match is in progress, I show the live score by running another PHP file (live_score.php). The two files interact thanks to the following script, present in the details.php file
$(document).ready(function(){
setInterval(function() {
var id=<?php echo"$id"?>;
var x = "<?php echo"$cod"?>";
$("#risultato").load("live_score.php", {var:id, x});
refresh();
}, 5000);
});
from details.php, I call live_score.php passing it some parameters.
These parameters are used by the live_score.php file to retrieve the score and other information in real time.
To print the result on the screen in details.php, I use a simple ECHO inside the live_score.php file, but I would like to retrieve this data and the others in a different way, via ajax if possible, but I don't know if it can be done and how....can you help me please? Thank you
I think you have already solved half of your problem. From your code , you should first remove the "refresh()" to stop reloading the page every 5 seconds.
then make sure that the the payload is correct, because the word "var" is a reserved keyword in JavaScript.
HTML
<div id="risultato"></div>
Javascript
$.ajax({
url: "live_score.php",
type: "POST",
data: { id, x},
success: function(response) {
//this response will be the data from "live_score.php"
//now assuming that
// 1. you use vanilla javascript with plain html + css
// 2. the returning reponse looks like this
// [{"teamName": "theTeam1", "score": 10}, {"teamName": "theTeam2", "score": 10}]
//Clear the current score
$("#risultato").empty();
// Now iterate through the response,
$.each(response, function(index, item) {
var teamName = item.teamName;
var score = item.score;
var html = "<p><strong>" + teamName + "</strong>: " + score + "</p>";
// this code will append (add to the end) the data iterated
$("#risultato").append(html);
});
},
error: function(xhr, status, error) {
//if your code or ajax call had any problems ,
//you can debug here and write error handling logic here, like
if(error){
alert("failed to fetch data");
console.log(error);
}
}
});

Pass data from jQuery to PHP file in one set

I have a table and some <td> have a data, but not all of them. On a button click I run jQuery function which checks each <td> and where the data is present, grabs the data.
After that the data is being passed to php file and inserted into my DB. Everything works great.
function insert_data() {
if(confirm("\nAre you sure?.\n")) {
$("#myTable td").each( function() {
var worker = $(this).attr("id");
var quarter = $(this).attr("title");
var station = $(this).attr("name");
var type = $(this).attr("class");
$.post({ url: "insert_data.php", data: {worker:worker, quarter:quarter, station:station, type:type} });
});
}
else { return false; }
}
I am wondering if instead of calling the php with ajax for every <td>, maybe there is a way to pass the data like one package? I checked at least couple dozen different articles here and on other websites and it seems that very often JSON is used for that purpose.
I've never worked with JSON and after several days of trying different approaches, still can't figure out what I am doing wrong. I will appreciate any help.
All I need is to pass data from my table into php file (and unpack it in there). I do not need to display it simultaneously on the html page.
Here is one of the versions which doesn't work:
JS:
function insert_data() {
if(confirm("\nAre you sure?.\n")) {
var myArray = []; // var to store all records for json data transfer
$("#myTable td").each( function() {
var worker = $(this).attr("id");
var quarter = $(this).attr("title");
var station = $(this).attr("name");
var type = $(this).attr("class");
var record = {worker:worker, quarter:quarter, station:station, type:type}; // sd - short for schedule data
myArray.push(record); // add every record to same array
});
console.log(myArray);
$.post({ url: "insert_data.php", data: {myArray: myArray }, success: function(data){ alert('Items added'); }, error: function(e){ console.log(e.message); } });
}
else { return false; }
}
In console I see following data (it looks like the data is being added to the array without issues):
(4) [{...}, {...}, {...}, {...}]
0: {worker: "556", quarter: "1", station: "abc_15", type: "rework"}
1: {worker: "147", quarter: "2", station: "abc_37", type: "rework"}
2: {worker: "345", quarter: "3", station: "abc_15", type: "rework"}
3: {worker: "12", quarter: "4", station: "abc_15", type: "rework"}
PHP:
$mySchedule = array();
$mySchedule[] = $_POST["myArray"]; // get the json array
var_dump($mySchedule);
foreach ($mySchedule as $sched) {
$worker = $sched['worker']; // or: $sched->worker; - doesn't change the result
$quarter = $sched['quarter'];
$station = $sched['station'];
$type = $sched['type'];
// code to insert data into my DB - works fine when I pass data one by one instead of array
}
HTML:
I also added this script to the page with my table:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-json/2.6.0/jquery.json.min.js"></script>
I am not sure if it is needed or not.
--
It feels that the problem is in the way how I "unpack" the array. But I am not sure... I tried to follow all advises I could find here, but maybe I just miss something really important.
I tried:
$mySchedule[] = json_decode($_POST["myArray"]); // in insert_data.php
data: { json: JSON.stringify(myArray) } // in jQuery function
and some other advises...
update
I got some help from one of my colleges. So, the jQuery code stayed without changes. PHP code had couple minor changes and it works fine now. The changes in PHP:
$mySchedule = $_POST["myArray"]; // get the json array
instead of:
$mySchedule = array();
$mySchedule[] = $_POST["myArray"]; // get the json array
That is it. Thank you very much for help and advises. I hope this example will be helpful to others.

Refresh div, but only if there is new content from php file

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

Return variable from an Ajax call is of invalid type for a JS date object

I am trying to get the server date and time using an Ajax call. I am able to retrieve the value I need, but when I try to use it to create a javascript date object, I get an invalid date error. I tried to use trim to remove any spaces too. Any ideas?
Ajax call:
// ajax call to getcurrent server time
$.ajax({
type: GET',
url: 'datetime.php',
success: function(data) {
console.log("Data: " + data);
currentdate = new Date($.trim(data));
console.log("Current date from server: " + currentdate);
},
});
PHP Code:
<?php
echo date('y,m,d,H,i,s');
?>
Console Output (Chrome):
Data: 12,06,08,15,07,57
Current date from server: Invalid Date
You are trying to use a string as if it were literal code. Kind of like using eval, but without actually including the eval.
Yes, eval is one way to do it: currentdate = eval("return new Date("+$.trim(data)+");");
However eval is evil. Instead, you should do:
var elems = $.trim(data).explode(",");
elems[1]--; // remember months are zero-based in JS
currentdate = new Date(elems[0],elems[1],elems[2],elems[3],elems[4],elems[5]);
Even better, though, would be to have your PHP script be echo time();, then your JS could be:
currentdate = new Date();
currentdate.setTime(data);

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