Reloads page once then reloads again without content change - javascript

I have a bit of javascript that posts to a php, every second, which checks a schedule and basically returns "refresh" if the start time is met then returns refresh when the end time is met.
if "refresh" it reloads the page showing what its suppose to.
function checkSchedules(){
if(sch_timer)
clearInterval(sch_timer)
$.ajax({
url:'checkSchedule_test.php?mediaID='+mediaIDArray[schCount],
type:'GET',
complete: function (response) {
if(response.responseText == "refresh"){
location.reload(true);
}
},
error: function () {
alert('Sorry there was an error!');
},
})
sch_timer = setTimeout(checkSchedules,1000);
schCount = (schCount >= urlArray.length - 1)? -1 : schCount
++schCount
}
in the php
if ($current_date>=$startDate && $current_date<=$endDate){
if ($current_time >= $startTime && $current_time <= $endTime){
$timeout = $endTime - $current_time;
if ($current_time >= $startTime && $current_time <= ($startTime+3000)){
echo "refresh";
}
if($timeout<=3000){
echo "refresh";
}
}
}
when the start time is met it refreshes fine, works great.
then when the end time is met it refreshes but the contents the same.
if I hit refresh it works fine.
I've tried different methods of reload() (document.reload, etc...)
Has anyone got any ideas?
Cheers

use console to understand what is returning from server
use debug() or console.log() for understand what is returning from php ... reload script is correct issue will be during ajax

Related

How to put the server's current timestamp into strtotime() function automatically PHP?

I am trying to make a program which counts down over the space of 15 seconds and displays them using PHP and JQuery. I need to be able to automatically load the server's timestamp into the strtotime function and set this to the start point of the timer, and make the end point of the timer 15 seconds after this point, is there any way I can achieve this?
I have tried setting the times specifically and the timer works for counting to 15 seconds after these points, but I need it to set these times relative to the current moment automatically, as I want it to start and stop the timer at certain undecided points in the program as it is running. I have also tried the reference values 'now' and '-15 seconds' - but these seem to stop the timer at '15 seconds remaining' and it does not count down from this point.
timer.php:
<?php
if(true) {
$countdownEnd = strtotime("-15 seconds");
$countdownStart = strtotime("now");
$timeLeft = $countdownEnd - $countdownStart;
if(isset($_POST["type"]) === true && $_POST["type"] == "timerupdate") {
echo ($timeLeft);
}
}
?>
timer.js:
$(function() {
var timerText = $("[timer]");
setInterval(function() {
$.post("timer.php", {type : "timerupdate"}, function(data){
timerText.html(data + " seconds remaining")
});
}, 1000);
});
timer tests.php:
<!DOCTYPE HTML>
<html>
<head>
<script type="application/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="application/javascript" src="timer.js"></script>
</head>
<body>
<?php include("timer.php") ?>
<p timer></p>
</body>
</html>
I expect the output to be a timer which counts down from 15 seconds whenever the starting condition (the if statement at the beginning of timer.php) becomes true.
Any help is really appreciated, thanks :)
If you want to save the timer after reload you need something like a session with a cookie. have a look at https://php.net/manual/en/function.session-start.php
//start a session and make sure there is no output before
session_start();
//maybe you want to check for the requestmethod before you do additional checks
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//your check for timerupdate.
//you dont have to exact bool compare to true the isset it can only return true or false.
if (isset($_POST["type"]) && $_POST["type"] == "timerupdate") {
if (!isset($_SESSION['time'])) $timeLeft = 15;
else $timeLeft = 15 - (time() - $_SESSION['time']);
//output the timer or whatever you want
if ($timeLeft < 0) echo 0;
else echo $timeLeft;
}
}
you have to add settings: withCredentials: true into your ajax call in order to send cookies
Can you check with using date function with time .

AJAX progress bar of load script

I have a big problem to make a progress bar in AJAX. The whole page is in AJAX, inside one of the webpage is AJAX which loads a function to get some big rows from the database.
I tried to make progress bar in this script in a foreach loop a flush() method and by writing/reading to $_SESSION, but still nothing. I really tried everything I don`t know how to do this. Need only this to complete my project. Could someone help me with this?
It is anyway which script I want to load, how is the template for this progress bar to use it in GET or POST ajax, for any AJAX.
<script>
jQuery(document).ready(function($) {
$(document).on('click','#save',function () {
setTimeout(getProgress,1000);
$(this).text('Pobieram analizę...');
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return decodeURI(results[1]) || 0;
}
}
var id = $.urlParam('id');
var idt = $.urlParam('idt');
$.ajax({
url: "views/getresults.php?id="+id+"&idt="+idt,
success: function(data) {
$("#loadresults").append(data);
}
});
setTimeout(getProgress,3000);
return false;
});
function getProgress(){
$.ajax({
url: 'views/listen.php',
success: function(data) {
if(data<=100 && data>=0){
console.log(data);
$('#loadresults').html('<div id="progress"><div class="progress-bar" role="progressbar" style="width:'+ (data / 100)*100 +'%">'+ data + '/' +100+'</div></div>');
setTimeout(getProgress,1000);
console.log('Repeat');
} else {
$('#loadresults').text('Pobieram dane');
console.log('End');
}
}
});
}
});
</script>
and here is a getresults.php
foreach($result as $resul) {
$count++;
session_start();
$_SESSION['progress'] = $count;
$_SESSION['total'] = 100;
session_write_close();
sleep(1);
}
unset($_SESSION['progress']);
and a get progress function listen.php
<?php
session_start();
echo (!empty($_SESSION['progress']) ? $_SESSION['progress'] : '');
if (!empty($_SESSION['progress']) && $_SESSION['progress'] >= $_SESSION['total']) {
unset($_SESSION['progress']);
}
?>
Writing and reading session doesn't work because the standard behavior of PHP is to lock the session file while your main code is being executed.
Try to create a file and update the its content with the percentage done during the execution of your function. Something like:
<?php
function slowFunction() {
$file = uniqid();
file_put_contents($file, 0);
// Long while that makes your stuff
// you have to know how many loops you will make to calculate the progress
$total = 100;
$done = 0;
while($done < $total) {
$done++;
// You may want not to write to the file every time to minimize changes of being writing the file
// at the same time your ajax page is fetching it, i'll let it to you...
$progress = $done / $total;
file_put_contents($file, $progress);
}
unlink($file); // Remove your progress file
}
?>
You can't get the progress of the data download from ajax. Once you request you to the server, the next response will be only after fetching the data or when the error occurs.
The solution to you is, get the data as fractions. Such as first download the 1/10th of the data, and in the success callback, recursively call the ajax again requesting the 2/10th data. On each success callback, you could change the progress bar.
Take a look at Server Side Events or Long polling as options

Notification on background PHP

I have a web application that use notification to inform user about anything new (just like Facebook).
My solution is that I send a request every three seconds to check the database if there is anything new to display (jQuery and AJAX). However, this makes the application slow, since a request is sent to check tables every three seconds.
I want to know how to make these notifications work without interrupting the application.
So this is my JS code:
jQuery(document).ready(function(){
LoopNotificationCRM();
});
function LoopNotificationCRM(){
setTimeout('LoopNotificationCRM();',3000);
$.ajax({
async: false,
type: "POST",
url: "controllers/c_ajax_notification.php",
data: "ordre=check_new_notification",
success: function(msg){
if(msg != 'NAN'){
var t = msg.split('***');
$('.sNotification').html(t[0]);
$('.ul-notification').html(t[1]);
$('.alert-notification').css('display','block');
}else{
$('.sNotification').html(0);
$('.alert-notification').css('display','none');
$('.ul-notification').html('');
}
},
error: function (xhr, status) {
alert('Erreur: ' + status);
}
});
}
And this is my PHP Code:
$notification->getNewNotification("*");
if($notification->db_num_row != 0){
$listNoti = '';
while($resN = $notification->fetch_array()){
$today = new DateTime(date('Y-m-d H:i:s'));
$datNoti = new DateTime($resN['date_not_crm']);
$diff = $datNoti->diff($today);
if($diff->d == 0){
if($diff->h == 0){
if($diff->i == 0){
$intervale = 'il y a '.$diff->s.' sec';
}else{
$intervale = 'il y a '.$diff->i.' min';
}
}else{
$intervale = 'il y a '.$diff->h.' heure(s)';
}
}else{
$intervale = 'il y a '.$diff->d.' jour(s)';
}
$listNoti .= '<li>
<a onclick="link(event,\''.$resN['url_not_crm'].'\');updateEtatNoti(this,'.$resN['id_not_crm'].');" style="cursor:pointer;">
<span class="label label-icon label-success"><i class="'.$resN['icon_not_crm'].'"></i></span>
'.$notification->csNotification($resN['description_not_crm']).'
<span class="time">'.$intervale.'</span>
</a>
</li>';
}
echo $notification->getCountNewNotification().'***'.$listNoti;
}else{
echo 'NAN';
}
When I remove the notification code my application become more fast !
If your application is slowing down when you run the ajax every 3 seconds, try simplifying/shrinking the amount of work the page loaded by the ajax needs to do. Rather than reading an entire table, for example, try selecting only notifications with a "read" status of 0. That way, the .php file is faster to execute, meaning the ajax will not slow down the page as much.

Php opens up a whole bunch of windows

I have a php script that I got from another guy and for some reason the login function does not work unless it opens up in a new window. (??? no idea why but that's just how it is) Anyways when I execute the open up window javascript from my PHP file, it opens up a whole bunch of windows. I figured that it was somehow looping, so I put the javascript function inside of a for loop that should only execute once. When I click my button, it opens up windows continously until I feverishly close them all and it stops.
Here is the code that seems to be the issue:
if(basename($_SERVER['PHP_SELF'])==USRFILE && (isset($_REQUEST['usr']) || isset($_REQUEST['susr']) || isset($_GET['mp']) || isset($_REQUEST['rc'])))
{
if(ISAJAX === 0) include(USRTEMPL.'head.php'); // if not Ajax request, include head.php (from USRTEMPL)
include(USRINCLS.'class.UsersReg.php'); // include the class for Register (used also for Recovery data)
ob_start(); // start storing output in buffer
// if 'susr'=Register, create objet of UsersReg (for Register)
// if 'rc' or 'mp' (for Recover-Confirma), uses UsersRecov class
// if 'usr', create object of UserPage class (for user page data)
if(isset($_REQUEST['susr']) && $_REQUEST['susr']==$lsite['users_logform']['register']) {
$objRe = new UsersReg($mysql);
echo $objRe->result;
for($x = 0; $x < 1; $x=2)
{
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?susr=Register');</script>";
}
}
else if(isset($_REQUEST['rc']) || isset($_GET['mp'])) {
include(USRINCLS.'class.UsersRecov.php'); //account recovery
$objRe = new UsersRecov($mysql);
for($x = 0; $x < 1; $x=2)
{
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?rc=Recover');</script>";
}
}
Specifically this section:
if(isset($_REQUEST['susr']) && $_REQUEST['susr']==$lsite['users_logform']['register']) {
$objRe = new UsersReg($mysql);
echo $objRe->result;
for($x = 0; $x < 1; $x=2)
{
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?susr=Register');</script>";
}
I tried looking up javascript opening up many windows but didn't find anything noteworthy. Same goes when I looked up php opening up a whole bunch of windows. It really makes no sense why it is looking, because it was looping before I put the for loop in. I put in the for loop to stop it, and it still loops.
If this code lives on or gets executed from users.php then that is your problem, because you would have an infinite loop.
The first line only runs this code on the users.php page (or it seems that way based on the constant name). The code goes on to say:
if(isset($_REQUEST['susr']) && $_REQUEST['susr']==$lsite['users_logform']['register']) {
I'm assuming that $lsite['users_logform']['register'] == 'Register'. Thus, when you visit users.php, this code runs. If the $_REQUEST['susr'] == 'Register' (because of the first page load that opened a new window to a url that matches users.php?susr=Regsiter), then you are instructing it to open ANOTHER instance of the page again, here:
if(isset($_REQUEST['susr']) && $_REQUEST['susr']==$lsite['users_logform']['register']) {
$objRe = new UsersReg($mysql);
echo $objRe->result;
for($x = 0; $x < 1; $x=2)
{
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?susr=Register');</script>";
}
}
IMO, you need to tell the second request to users.php (generated by your javascript bit) that it is from javascript. Then ignore your entire code block if it is from javascript. Something like this should work:
if ( !isset($_GET['from_js']) && basename($_SERVER['PHP_SELF'])==USRFILE && ( isset($_REQUEST['usr']) || isset($_REQUEST['susr']) || isset($_GET['mp']) || isset($_REQUEST['rc']) ) )
{
if(ISAJAX === 0) include(USRTEMPL.'head.php'); // if not Ajax request, include head.php (from USRTEMPL)
include(USRINCLS.'class.UsersReg.php'); // include the class for Register (used also for Recovery data)
ob_start(); // start storing output in buffer
// if 'susr'=Register, create objet of UsersReg (for Register)
// if 'rc' or 'mp' (for Recover-Confirma), uses UsersRecov class
// if 'usr', create object of UserPage class (for user page data)
if(isset($_REQUEST['susr']) && $_REQUEST['susr']==$lsite['users_logform']['register']) {
$objRe = new UsersReg($mysql);
echo $objRe->result;
// there is no reason for the for loop. totally pointless
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?susr=Register&from_js=1');</script>";
}
else if(isset($_REQUEST['rc']) || isset($_GET['mp'])) {
include(USRINCLS.'class.UsersRecov.php'); //account recovery
$objRe = new UsersRecov($mysql);
// there is no reason for the for loop. totally pointless
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?rc=Recover&from_js=1');</script>";
}
}
Ok. I changed the first line to include a check for the $_GET['from_js'] variable. I removed the for loops, because they are totally pointless, since they only ever run once. To the urls that are opened in the new window, I added &from_js=1. With this, your code does not run on the subsequent new window openings. This will prevent the infinite popups.
Hopefully this helps.
Change
echo "<script type='text/javascript'>window.open('http://www.thelegendmaker.net/users.php?susr=Register');</script>";
to:
header('Location: users.php?susr=Register');

PHP Comet cause page reload slow

Hi I am tring to implement the comet with PHP and jquery. The comet is started on every page load. However it cause loading of any page in the website become very slow like 10 seconds, it seem to be waiting for the previous request to the server to die() at the if($elapse > 10)
But if a ajax connection connection is aborted, isn't the PHP should stop executing furher ? Any idea why reloading page become slow ?
function getPendingCheckin()
{
ignore_user_abort(false);
$iCreatedDate = $this->input->post("iLastCreateDate");
$aCheckin = [];
$prev = time();
while(! $aCheckin )
{
$aCheckin = $this->getData();
if($aCheckin || connection_aborted() == 1)
{
break;
}
else
{
sleep(1);
$elapse = time() - $prev;
if($elapse > 10)
{
die();
}
}
}
header('Content-type: application/json');
echo json_encode($aCheckin);
}
Javascript
$(window).ready(function(){
var iLastCreateDate = $('#iLastCreateDate').val();
function startGetPendingCheckin()
{
$.ajax({
type: "POST",
url: "/kc/comet/getPendingCheckin",
data: 'iLastCreateDate=' + iLastCreateDate,
error : function(msg)
{
//alert("Error get pending checkin");
},
success :function(o)
{
if(o)
{
//process data
}
startGetPendingCheckin();
}
});
}
startGetPendingCheckin();
})
No, php execution is not (always) aborted. I noticed that on heavy scripts runned on local machine.
You may fail to run 2 parallel request to php scripts due to not closed session. Usually it is auto-closed after termination of the script. With default behavior (sessions in lockable files, no manual closing) it is not possitble to have 2 simultaneous requests from the same user — the latter would be blocked by the former and will wait for its termination.
You may close session as long as you checked everything about user authorization.

Categories

Resources