I'm using this jquery timer to collect time spent while it is running.
https://github.com/walmik/timer.jquery
http://jquerytimer.com/
In a prior Stack Overflow post we were able to Post to another page the current accumulated time using jQuery Ajax (jQuery.timer how to get current value in php?). Many thinks to #Dakis
It seems our current solution is trying to save on any Stop and Restart of the Timer. It only needs to do a Save to DB routine IF the “Save Time and Notes” button is selected.
I’ve been researching jQuery Ajax and understand that a key/value pair is needed to be sent to the server/receiving page. I understand the first value identifies the target from which to get the "key", but I could not get a clear understanding of proper formatting for the second “value”.
'task': $('.ta_tasks').data('task’) does not seem to be passing the value as expected.
I’ve added a TextArea with an ID of “ta_tasks” and appended the current working AJAX with:
data: {
'time': $('.timer').data('seconds'),
'state': $('.timer').data('state'),
'task': $('.ta_tasks').data('task’)
On the receiving page I added a simple alert to see if the value is being received but it is not. If I can figure out how to properly send the contents of the TextArea I could also figure out how to submit a value from the “Save Time and Notes” button so that a Pause and Restart will not also submit to the database.
Working page: http://sgdesign.com/timer2.php
Parent page script:
<script src="https://cdnjs.cloudflare.com/ajax/libs/timer.jquery/0.7.1/timer.jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var hasTimer = false;
/**
* Save the current timer value.
*
* Performs an ajax request to the server, which will
* save the timer value in a database table and return
* a corresponding message.
*/
function saveTime() {
$.ajax({
method: 'post',
dataType: 'html',
url: 'saveTime.php',
data: {
'time': $('.timer').data('seconds'),
'state': $('.timer').data('state'),
'task': $('.ta_tasks').data('task')
},
success: function (response, textStatus, jqXHR) {
displayAlert('success', response);
},
error: function (jqXHR, textStatus, errorThrown) {
/*
* If the status code of the response is the custom one
* defined by me, the developer, in saveTime.php, then I
* can display the corresponding error message. Otherwise,
* the displayed message will be a general user-friendly
* one - so, that no system-related infos will be shown.
*/
var message = (jqXHR.status === 420)
? jqXHR.statusText
: 'An error occurred during your request. Please try again.';
displayAlert('danger', message);
},
complete: function (jqXHR, textStatus) {
//...
}
});
}
/**
* Display a bootstrap alert.
*
* #param type string success|info|warning|danger.
* #param message string Alert message.
* #return void
*/
function displayAlert(type, message) {
var alert = '<div class="alert alert-' + type + ' alert-dismissible" role="alert">'
+ '<button type="button" class="close" data-dismiss="alert" aria-label="Close">'
+ '<span aria-hidden="true">×</span>'
+ '</button>'
+ '<span>' + message + '</span>'
+ '</div>';
$('.messages').html(alert);
}
// Init timer start
$('.save-timer-btn').on('click', function () {
saveTime();
});
// Init timer start
$('.start-timer-btn').on('click', function () {
hasTimer = true;
$('.timer').timer({
editable: true
});
$(this).addClass('d-none');
$('.pause-timer-btn').removeClass('d-none');
});
// Init timer resume
$('.resume-timer-btn').on('click', function () {
$('.timer').timer('resume');
$(this).addClass('d-none');
$('.pause-timer-btn').removeClass('d-none');
});
// Init timer pause
$('.pause-timer-btn').on('click', function () {
$('.timer').timer('pause');
$(this).addClass('d-none');
$('.resume-timer-btn').removeClass('d-none');
saveTime();
});
// Remove timer. Leaves the display intact.
$('.remove-timer-btn').on('click', function () {
hasTimer = false;
$('.timer').timer('remove');
$(this).addClass('d-none');
$('.start-timer-btn').removeClass('d-none');
$('.pause-timer-btn, .resume-timer-btn').addClass('d-none');
});
// Additional focus event for this demo
$('.timer').on('focus', function () {
if (hasTimer) {
$('.pause-timer-btn').addClass('d-none');
$('.resume-timer-btn').removeClass('hidden');
}
});
// Additional blur event for this demo
$('.timer').on('blur', function () {
if (hasTimer) {
$('.pause-timer-btn').removeClass('d-none');
$('.resume-timer-btn').addClass('d-none');
}
});
});
</script>
Target Page contents:
<?php
// Price per hour variable
$cost = 50;
# require 'connection.php';
// Validate the timer value.
if (!isset($_POST['time']) || empty($_POST['time'])) {
/*
* This response header triggers the ajax error because the status
* code begins with 4xx (which corresponds to the client errors).
* I defined 420 as the custom status code. You can choose whatever
* code between 401 and 499 which is not officially assigned, e.g.
* which is marked as "Unassigned" in the official HTTP Status Code Registry.
* See the link.
*
* #link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml HTTP Status Code Registry.
*/
header('HTTP/1.1 420 No time value defined. Did you start the timer?');
exit();
}
// Validate the timer state.
if (!isset($_POST['state']) || empty($_POST['state'])) {
header('HTTP/1.1 420 No timer state recognized. Did you start the timer?');
exit();
}
// Read the posted values.
$time = $_POST['time'];
$state = $_POST['state']; /* The state of the timer when the saving operation was triggered. */
$task = $_POST['ta_tasks'];
$r = $cost / 3600 * $time;
$rate = round($r, 2);
/*
* Save the timer value in a db table using PDO library.
*/
/* $sql = 'INSERT INTO my_timer_table (
time
) VALUES (
:time
)';
$statement = $connection->prepare($sql);
$statement->execute([
':time' => $time,
]);
// Print success message.
echo 'Time (' . $time . ' seconds) successfully saved when timer was ' . $state . '.';
exit(); */
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script>
var a = "<?php echo $task; ?>";
alert ('task: ' + a);
</script>
</head>
<body>
<?php function secondsToTime($seconds) {
$dtF = new \DateTime('#0');
$dtT = new \DateTime("#$seconds");
return $dtF->diff($dtT)->format('%h hours, %i minutes and %s seconds');
// return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
}
?>
<?php echo secondsToTime($time);
echo '<br>';
echo 'Tasks: '.$task .'<br>';
echo 'Cost: $'. $rate;
?>
</body>
</html>
Goal Summary
Proper formatting of data in: 'task': $('.ta_tasks').data('task’)
Understanding of Why so as to learn how to also transfer when the 'Save Time and Notes" button to invoke saving Cost and Notes to DB
Don't define functions inside $(document).ready. Bring them outside.
Functions in PHP should reside only in pages destined for this purpose. See PSR-1 Side Effects. In principle you should definitely read: PSR-1 and PSR-2. Optional, especially PSR-4.
When you try to read a value sent through ajax, then you should read the value, not the CSS selector. So: Wrong: $task = $_POST['ta_tasks'];, correct: $task = $_POST['task'];.
Before validating posted values (on top of the page saveTime.php) you shouldn't declare any variables or do other things - so to say. So no $cost = 50; before validations, but after them. Still, if you want to define constants for saveTime.php, then better bring them in another file, which you can include.
In this case, the data() method is a proprietary method of http://jquerytimer.com ! You can use it to fetch some values (timer value, timer state, etc). But, in order to fetch the value of a html control you need to use val(), or text(), or innerHtml, etc. In a word: native js or jquery methods/functions. So, use like this:
data: {
'time': $('.timer').data('seconds'),
'state': $('.timer').data('state'),
'task': $('#ta_tasks').val()
}
Do you see the selector ('#ta_tasks')? It references an id (because of #). You used .ta_tasks, therefore referencing a class name. Which you didn't define.
Better: use the camelCase naming convention for html id's and names, and the "hyphen-separated" form for css classes:
data: {
'time': $('.timer').data('seconds'),
'state': $('.timer').data('state'),
'task': $('#ta_tasks').val()
}
//...
<textarea id="taTasks" name="taTasks" class="form-control" rows="4">Doh!</textarea>
Avoid as much as possible referencing php code from javascript or css code. If you need a php value inside a javascript code, then pass it through a javascript function - as argument, or save the php value inside an attribute of a html control and read it through referencing the attribute by js/jquery methods/functions. As an example, see the code in saveTime.php, which saves the task value in a hidden input and alerts it from js code.
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo - Timer</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/timer.jquery/0.7.1/timer.jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var hasTimer = false;
// Init timer start
$('.save-timer-btn').on('click', function () {
saveTime();
});
// Init timer start
$('.start-timer-btn').on('click', function () {
hasTimer = true;
$('.timer').timer({
editable: true
});
$(this).addClass('d-none');
$('.pause-timer-btn').removeClass('d-none');
});
// Init timer resume
$('.resume-timer-btn').on('click', function () {
$('.timer').timer('resume');
$(this).addClass('d-none');
$('.pause-timer-btn').removeClass('d-none');
});
// Init timer pause
$('.pause-timer-btn').on('click', function () {
$('.timer').timer('pause');
$(this).addClass('d-none');
$('.resume-timer-btn').removeClass('d-none');
saveTime();
});
// Remove timer. Leaves the display intact.
$('.remove-timer-btn').on('click', function () {
hasTimer = false;
$('.timer').timer('remove');
$(this).addClass('d-none');
$('.start-timer-btn').removeClass('d-none');
$('.pause-timer-btn, .resume-timer-btn').addClass('d-none');
});
// Additional focus event for this demo
$('.timer').on('focus', function () {
if (hasTimer) {
$('.pause-timer-btn').addClass('d-none');
$('.resume-timer-btn').removeClass('d-none');
}
});
// Additional blur event for this demo
$('.timer').on('blur', function () {
if (hasTimer) {
$('.pause-timer-btn').removeClass('d-none');
$('.resume-timer-btn').addClass('d-none');
}
});
});
/**
* Save the current timer value.
*
* Performs an ajax request to the server, which will
* save the timer value in a database table and return
* a corresponding message.
*/
function saveTime() {
$.ajax({
method: 'post',
dataType: 'html',
url: 'saveTime.php',
data: {
'time': $('.timer').data('seconds'),
'state': $('.timer').data('state'),
'task': $('#taTasks').val()
},
success: function (response, textStatus, jqXHR) {
displayAlert('success', response);
},
error: function (jqXHR, textStatus, errorThrown) {
var message = (jqXHR.status === 420)
? jqXHR.statusText
: 'An error occurred during your request. Please try again.';
displayAlert('danger', message);
},
complete: function (jqXHR, textStatus) {
//...
}
});
}
/**
* Display a bootstrap alert.
*
* #param type string success|info|warning|danger.
* #param message string Alert message.
* #return void
*/
function displayAlert(type, message) {
var alert = '<div class="alert alert-' + type + ' alert-dismissible" role="alert">'
+ '<button type="button" class="close" data-dismiss="alert" aria-label="Close">'
+ '<span aria-hidden="true">×</span>'
+ '</button>'
+ '<span>' + message + '</span>'
+ '</div>';
$('.messages').html(alert);
}
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12">
<h4>
Timer Demo 2
</h4>
</div>
</div>
<div class="row">
<div class="col-xs-6 messages"></div>
</div>
<div class="row">
<div class="col-md-3">
<input type="text" id="timer" name="timer" class="form-control timer" placeholder="0 sec">
</div>
<div class="col-md-9">
<button type="button" class="btn btn-success start-timer-btn">
Start
</button>
<button type="button" class="btn btn-success resume-timer-btn d-none">
Resume
</button>
<button type="button" class="btn btn-danger pause-timer-btn d-none">
Pause
</button>
<button type="button" class="btn btn-danger remove-timer-btn d-none">
Remove Timer
</button>
<button type="button" class="btn btn-primary save-timer-btn">
Save Time and Notes
</button>
</div>
</div>
<div class="row mt-1">
<div class="col-sm-12">
<lable for="taTasks">Notes to accompany task:</lable>
<textarea id="taTasks" name="taTasks" class="form-control" rows="4">Doh!</textarea>
</div>
</div>
</div>
</body>
</html>
saveTime.php
<?php
require_once 'functions.php';
// Validate the timer value.
if (!isset($_POST['time']) || empty($_POST['time'])) {
header('HTTP/1.1 420 No time value defined. Did you start the timer?');
exit();
}
// Validate the timer state.
if (!isset($_POST['state']) || empty($_POST['state'])) {
header('HTTP/1.1 420 No timer state recognized. Did you start the timer?');
exit();
}
// Validate the task.
if (!isset($_POST['task']) || empty($_POST['task'])) {
header('HTTP/1.1 420 No task value received.');
exit();
}
// Price per hour variable
$cost = 50;
// Read the posted values.
$time = $_POST['time'];
$state = $_POST['state']; /* The state of the timer when the saving operation was triggered. */
$task = $_POST['task'];
$r = $cost / 3600 * $time;
$rate = round($r, 2);
?>
<script type="text/javascript">
$(document).ready(function () {
alertTask();
});
function alertTask() {
var task = $('#task').val();
alert(task);
}
</script>
<input type="hidden" id="task" name="task" value="<?php echo $task; ?>">
<?php
echo secondsToTime($time);
echo '<br>';
echo 'Tasks: ' . $task . '<br>';
echo 'Cost: $' . $rate;
?>
functions.php
<?php
function secondsToTime($seconds) {
$dtF = new \DateTime('#0');
$dtT = new \DateTime("#$seconds");
return $dtF->diff($dtT)->format('%h hours, %i minutes and %s seconds');
// return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
}
Edit 1: In index.php, I brought the js functions outside of $(document).ready. I forgot to do it earlier.
Edit 2: Changed hidden to d-none in
$('.resume-timer-btn').removeClass('hidden');
Edit 3: I found the problem about which I commented. It was in my saveTime.php code: I loaded the jquery library, but it was already loaded in index.php. More of it: since you are loading the content of saveTime.php in a html page (index.php) which already has all resources loaded, you don't need to structure the saveTime.php as a whole structured html (with doctype, head, body, etc). It is completely enough to just define the content and script tags that you need. So, I reedited saveTime.php correspondingly.
textarea don't have ta_tasks class, u use id and it doesn't have html5 data object, correct to $("#ta_tasks").val().
check your ajax request data that you re sending and the one you are getting in your saveTime.php, you are sending 'task' and receiving 'ta_task' in saveTime.php
$.ajax({
method: 'post',
dataType: 'html',
url: 'saveTime.php',
data: {
'time': $('.timer').data('seconds'),
'state': $('.timer').data('state'),
'ta_task': $('.ta_tasks').data('task')
},
//other codes here
//saveTime.php
//now get the value with 'ta_task'
$task = $_POST['ta_task'];
Related
I'm working on a notification message i want to load new message from a page call check_new-reply.php in every 10 second using Ajax and Jquery but my code is not showing anything i don't know what the error is please can someone help me out?
<script>
$(document).ready(function(){
$(function(){
var timer = 10;
var test = "";
function inTime(){
setTimeOut(inTime, 1000);
$("#timer-u").html("Time refreshing"+timer);
if(timer == 8){
$("#message-u").html("Loading....");
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
})
timer = 11;
clearTimeout(inTime);
}
timer--;
}
inTime();
});
});
</script>
Here is PHP
<?php include($root . '_inc/Initialization.php');?>
<?php require_once("_inc/dbcontroller.php"); $db_handle = new DBController();?>
<?php
$users = $_SESSION['username'];
$newquery = "SELECT * FROM blog_post
INNER JOIN replys
ON blog_post.UserName = '$users'
WHERE replys.read = 0
ORDER BY rtime";
$newhisory = mysql_query($newquery);
while($newrow = mysql_fetch_array($newhisory)){
echo '<div class="fnot">'.htmlentities($newrow['blog_title']).'';
echo '<span class="ttcredit"><font color="darkgreen">94</font> </span> <a class="reqttag reqttag2" href="#">No</a> ';
echo '</div>';
echo '<input type="hidden" id="unr" name="unr" value="'.$newrow['BID'].'"/>';
}
?>
If you just want to call it every 10 seconds, use 10000 milliseconds in the setTimeOut . Also, it is best to call again the function only when the previous Ajax call is done:
$(document).ready(function(){
$(function(){
var test = "";
function inTime(){
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
setTimeout(inTime, 10000);
});
}
inTime();
});
});
To call any function with some intervals you will have to use
<script>
$(document).ready(function(){
window.setInterval(function(){
myAjaxCall();
}, 10000);
});
function myAjaxCall() {
alert("Hi");
$("#message-u").html("Loading....");
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
});
}
</script>
window.setInterval will call your function on every 3 seconds with above code, and will generate an alert message,
what you have to do is set your ajax code in a function and use above method, change 3000 to 10000 and your ajax call will defiantly work with every 10 seconds,
This is the code which will call our javascript function on every 10 seconds,
just copy it and check it, you will get an idea, also i have included the jquery as we have discussed.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
</body>
<script>
$(document).ready(function(){
window.setInterval(function(){
myAjaxCall();
}, 3000);
});
function myAjaxCall() {
alert("Call your Ajax here");
$("#message-u").html("Loading....");
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
});
}
</script>
I'm affronted to another jQuery problem. Well I'm beginning by my code to understand my issue here:
<script type="text/javascript">
jQuery(document).ready(function() {
var current = <?php echo ($_GET['page']!='') ? $_GET['page'] : 1; ?>;
var idp;
$(window).scroll(function(e){
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
current=current+1;
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
e.preventDefault();
}
if($(window).scrollTop() == 0) {
current=((current-1)<=0) ? 1 : current-1;
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
e.preventDefault();
}
});
window.onpopstate = function(event) {
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
};
function loadMoreContent(position) {
$('#loader').fadeIn('slow', function() {
$.get("index.php"+position+" #annonceis", function(data){
var dato = $(data).find("#annonceis");
$("#annonceis").html(dato);
$('#loader').fadeOut('slow', function() {
$(window).scrollTop(60);
});
});
});
}
});
</script>
My problem is based on infinite scroll but instead of "append" I used html() function to replace content in a div called annonceis.
The idea is that when I'm scrolling to bottom of the page I get content of new page called index.php?page=1 2 3. And replace old content in de div annonceis with the new content that I get with jQuery, but when I scroll to the bottom I Get content of next next page ex when the current page is index.php?page=2 normally when I scroll to bottom I must get content of index.php?page=3 but here I get content of index.php?page=3 and instantly index.php?page=4 so the page display index.php?page=4.
The main idea is scrolling to bottom and get the content of the next page instead of pagination, but it must take care about history.pushState for SEO purpose and Google suggestions see http://scrollsample.appspot.com/items and that https://googlewebmastercentral.blogspot.com/2014/02/infinite-scroll-search-friendly.html.
Thank you very much in advance.
So, what you're after really is pagination combined with infinite scroll. What the provided example is doing is using .pushState() to track the users scroll using page Waypoints. Notice, once page X reaches the center point in the page, the .pushState() is triggered.
Secondly, if you look at the example's source code for any of the pages, you'll see it will only render the selected page, then using listeners on the .scroll it will append or prepend content as needed.
So, at it's core, this is really just simple pagination. The infinite scroll feel is simply added on top for user experience. Basic overview to do this would look something like this:
Model or Controller
Your PHP file or whatnot, that runs the actual queries - class based for ease of use. The class will contain one function to grab a set of posts based on a request page. JavaScript will handle everything else.
<?php
Class InfiniteScroller {
// Set some Public Vars
public $posts_per_page = 5;
public $page;
/**
* __construct function to grap our AJAX _POST data
*/
public function __construct() {
$this->page = ( isset($_POST['page']) ? $_POST['page'] : 1 );
}
/**
* Call this function with your AJAX, providing what page you want
*/
public function getPosts() {
// Calculate our offset
$offset = ($this->posts_per_page * $this->page) - $this->posts_per_page;
// Set up our Database call
$SQL = "SELECT * FROM my_post_table ORDER BY post_date ASC LIMIT " . $offset . ", " . $this->posts_per_page;
// Run Your query, format and return data
// echo $my_formatted_query_return;
}
}
?>
AJAX Call
The next thing you'll want to take care of is your frontend and JavaScript, so your AJAX call can sit in a function that simply calls the above method and takes a page parameter.
<script type="text/javascript">
function getPageResults( page = 1, arrange = 'next' ) {
$.ajax({
url: url;
type: "POST",
data: "?page=" + page,
success: function(html) {
/* print your info */
if( arrange == 'prev' ) {
$( '#myResults' ).prepend(html);
else if( arrange == 'next' ) {
$( '#myResults' ).append(html);
}
},
error: function(e) {
/* handle your error */
}
});
}
</script>
The HTML View
Your HTML would be fairly basic, just a place to hold your displayed results and some creative triggers.
<html>
<head>
</head>
<body>
<div class="loadPrev"></div>
<div id="myResults">
<!-- Your Results will show up here -->
</div>
<div class="loadNext"></div>
</body>
</html>
Loading the Page You Want
In basic summation, the last piece of your puzzle is loading the page requested based on the querystring in the URL. If no querystring is present, you want page 1. Otherwise, load the requested page.
<script type="text/javascript">
$( document ).ready(function() {
var page = <?php echo ( isset($_GET['page'] ? $_GET['page'] : 1) ?>;
getPageResults( page, 'next' );
});
</script>
After that you can set up some creative listeners for your previous and next triggers and call the getPageResults() with the needed page, and the next or prev attribute as needed.
This can really be done in a much more elegant sense - look at the JS from the example you provided: http://scrollsample.appspot.com/static/main.js
Cleaning it up
Once you have the basic architecture in place, then you can start altering the .pushState() as well as changing out the canonical, next, and prev <link rel> header items. Additionally at this point you can start to generate the next / prev links you need, etc. It should all fall into place once you have that basic foundation laid.
Hey Bro #LionelRitchietheManatee Finnaly I have resolved the problem this is the code that I used.
<script type="text/javascript">
jQuery(document).ready(function() {
var current = <?php echo ($_GET['page']!='') ? $_GET['page'] : 1; ?>;
var idp;
var loaded = true;
$(window).scroll(function(e){
if(($(window).scrollTop() + $(window).height() == $(document).height())&&(loaded)) {
loaded = !loaded;
current=current+1;
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
e.preventDefault();
}
if($(window).scrollTop() == 0) {
loaded = !loaded;
current=((current-1)<=0) ? 1 : current-1;
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
e.preventDefault();
}
});
window.onpopstate = function(event) {
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
};
function loadMoreContent(position) {
$('#loader').fadeIn('slow', function() {
$.get("index.php"+position+" #annonceis", function(data){
var dato = $(data).find("#annonceis");
$("#annonceis").html(dato);
$('#loader').fadeOut('slow', function() {
loaded = !loaded;
$(window).scrollTop(60);
});
});
});
}
});
</script>
I had added a new var called "loaded" with initial value as TRUE, and it will be updated to FALSE state when content is loaded, and to the TRUE state when we begin scrolling.
I'ts very primitive as solution not very clean work as you did but it solved my problem.
Thank you anyway for your help, you are the BOSS.
So I have been making a chat and at 14:09 it was working fine, it displayed messages, received them and stored them in DB. It also displayed stored messages and showed users the messages instantly. However suddenly it just stop showing all the messages. I have checked and the messages are stored in the DB when sent. I dunno what the error is as I've not changed the code to affect it. It would help a lot if you could help me with this! :)
index.php (includes AJAX jQuery & form)
<div id="messageSend">
<form action="shout.php" method="post" id="chat">
<textarea rows="8" cols="74" id="Message" name="Message" placeholder="Post messages here."></textarea>
<br/><input type="submit" id="submit" value="Shout!">
</form>
<script>
$('#chat').submit(function(e) {
e.preventDefault();
var form = $('#chat'),
url = form.attr('action'),
Message = $('#Message');
$.post(url, {Message : Message.val()}, function(data) {
$('#messageDisplay').html(data);
$('#Message').empty().val('');
});
setInterval(function() {
// Do something every 2 seconds
{
$.get("data.php").done(function(data) {
$('#messageDisplay').html(data);
});
}
}, 1000);
});
</script>
shout.php (send message and adds to DB)
<?php
include 'auth.login.php';
include 'pdo.config.php';
if (!isset($_SESSION['Username'])) {
echo '<br/>';
echo '<center>You need to login to post!<br/>';
header("Refresh:2; URL=index.php");
exit();
}
if (!isset($_POST['Message']) || empty($_POST['Message'])) {
echo '<br/>';
echo '<center>Message box empty!<br/>';
exit();
}
$Username = $_SESSION['Username'];
$Message = htmlspecialchars(trim($_POST['Message']));
$insertMessage = $PDO->prepare("INSERT INTO `chatbox` (User, Message) VALUES (?, ?)");
$insertMessage->bindParam(1, $Username, PDO::PARAM_STR);
$insertMessage->bindParam(2, $Message, PDO::PARAM_STR);
$insertMessage->execute();
?>
data.php (file which has loop to retrieve messages from DB)
<?php
include 'pdo.config.php';
$chat = $PDO->query("SELECT * FROM `chatbox`");
while($getRow = $chat->fetch(PDO::FETCH_ASSOC)) {
echo '['.date('d/m/Y g:i:s A', strtotime($getRow['SentOn'])).'] '.$getRow['User'].': '.stripslashes($getRow['Message']).'<br/>';
}
?>
Your page data.php is not being called. The contents are these:
[05/09/2013 10:37:31 AM] test: test
[05/09/2013 10:37:44 AM] test: test
So, they are being inserted properly; however, when a user clicks "Shout" it does not call the setInterval().
Edit: Your problem is that after they login, the setInterval() isn't called. If you refresh the page after logging in, it will work (works for me).
Try this:
$(document).ready(function() {
$('#chat').submit(function(e) {
e.preventDefault();
var form = $('#chat');
url = form.attr('action');
Message = $('#Message');
$.post(url, {Message : Message.val()}, function(data) {
$('#messageDisplay').html(data);
$('#Message').empty().val('');
});
setInterval(function() {
// Do something every 2 seconds
$.get("data.php").done(function(data) {
$('#messageDisplay').html(data);
});
}, 1000);
});
<?php if (isset($_SESSION['Username'])) { ?>
setInterval(function() {
// Do something every 2 seconds
$.get("data.php").done(function(data) {
$('#messageDisplay').html(data);
});
}, 1000);
<?php } ?>
});
I am working on the PHP cart timer script using PHP and jQuery/JavaScript.
I am iterating the set-interval function every seconds to get the PHP's current time-stamp.
When the first product is added to the cart, the timer begins before getting timer-stops it prompts the user, whether the user want to continue or cancel.
My code is follows
$(document).ready(function(){
var orderedtime = "echo $_SESSION['ordertime'];";
if (orderedtime === null || orderedtime == ''){
console.log("orderedtime is not set");
}
else{
init();
}
});
var currenttime;
var alerttime;
var extratime;
function cd(){
alerttime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (1 * 60))); ?>"
extratime = "<?php echo date('h:i:s', (strtotime($_SESSION['ordertime']) + (2 * 60))); ?>";
redo();
}
function redo(){
currenttime = "<?php echo date('h:i:s', time()); ?>";
if(alerttime == currenttime) {
//doing something
}
else if(currenttime == extratime){
//doing something
}
else{
cd = setTimeout("redo()",1000);
}
}
function init(){
cd();
}
The currenttime variable only storing the 1st iteration value is not getting updating.
How to solve this issue?
Please kindly help me to solve it.
Thanks in advance.
You're not actually requesting a time from the server in your setTimeout loop.
This line
currenttime = "<?php echo date('h:i:s', time()); ?>";
is set when the page is first generated and not changed again. If you want the time updated you need to send a request to the server. This probably isn't the best way to do it though.
Further to MikeW's excellent but incomplete answer, you need a way to request the time from the server and receive it back in the DOM.
There is only one way to do that: AJAX.
As Mike pointed out, the PHP code that you typed above only runs once: when the page is first generated. After the page has been generated and the document is "ready", you must use AJAX.
Below is a fully-working, copy/pastable example to demonstrate one way this could work.
Note that I had to over-ride the orderedtime variable because I don't know how/when you set that.
HTML/javascript side: index.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
#timeDiv{width:40%;height:200px;background:wheat;padding:10px;}
</style>
<script type="text/javascript">
$(document).ready(function() {
//var orderedtime = "<?php echo $_SESSION['ordertime']; ?>";
var orderedtime = '';
if (orderedtime === null || orderedtime == ''){
console.log("orderedtime is not set");
}else{
doAjax();
}
window.setInterval(function(){
doAjax();
},2000);
}); //END document.ready
function doAjax() {
$.ajax({
type: "POST",
url: "get_the_time.php",
data: "ordertime=" + orderedtime,
success: function(myData) {
$('#thetime').html(myData);
}
});
}
</script>
</head>
<body>
<div id="timeDiv">
The time is: <span id="thetime"></span>
</div>
</body>
</html>
PHP side: get_the_time.php
<?php
if (isset($_POST['ordertime']) != true) {
$d = date("h:i:s");
}else{
$ot = $_POST['ordertime'];
$d = date('h:i:s', (strtotime($ot) + (1 * 60)));
}
echo $d;
IMPORTANT NOTE:
When using AJAX, the response sent from the server is received inside the success: function, and no where else.
If you later wish to use that data, assigning it into a variable inside the success function will not work. The best way I have found is to stick the received data into an element of some kind (a hidden input field works great for this), and then retrieve it from there when needed.
For example:
<input type="hidden" id="myHiddenField" />
$.ajax({
type: "POST",
url: "get_the_time.php",
data: "ordertime=" + orderedtime,
success: function(myData) {
$('#thetime').html(myData);
$('#myHiddenField').val(myData);
}
});
Then, inside some other javascript function, you can grab that data and assign it to some variable, thus:
var someVar = $('#myHiddenField').val();
Hope this helps, late as it is.
This stackoverflow post has further information/explanation regarding AJAX. Check out the simplified AJAX examples at the bottom.
After a lot of trials, I am successfully able to maintain continuous server connection with a database.
Now code keep checking and show the messages, if there are new in database.
Please review and tell:
if there is true long polling technique used in this code? If it is not, then please suggest, where I am wrong(deviating from long polling) and how this can be made a true long polling.
Currently, I am getting these errors. However still it maintains the continous connection with database.
**each time only one message is pulled instead of all **(I used each loop but it stops the long polling)
After every 10/15 seconds, token error appeares (Parse error (syntax error=unexpected token)).
var last_msg_id = 2;
function load_msgs() {
$.ajax({
type:"Post",
url:"getdata.php",
data:{
last_msg_id:last_msg_id
},
dataType:"json",
async:true,
cache:false,
success:function(data) {
var json = data;
$("#commidwin").append(json['msg']);
last_msg_id = json["last_msg_id_db"];
setTimeout("load_msgs()", 1000);
},
error:function(XMLhttprequest, textstatus, errorthrown) {
alert("error:" + textstatus + "(" + errorthrown + ")");
setTimeout("load_msgs()", 15000);
}
});
}
Php file is here
$last_msg_id=$_POST['last_msg_id'];
$last_msg_id_db=1;
while($last_msg_id>$last_msg_id_db){
usleep(10000);
clearstatcache();
$sql=mysqli_query($db3->connection,"SELECT * FROM chat_com where id>'$last_msg_id' ORDER by id ASC");
$sql_m=mysqli_query($db3->connection,"SELECT max(id) as maxid FROM chat_com");
$row_m=mysqli_fetch_array($sql_m);
$last_msg_id_db=$row_m['maxid'];
while($row=mysqli_fetch_array($sql)){
$textt=$row['mesg'];
$last_msg_id_db=$last_msg_id_db;
$response=array();
$response['msg']=$textt;
$response['last_msg_id_db']=$last_msg_id_db;
}
}
echo json_encode($response);
Polling is a bit harder than a simple while : just because generally all things you output to the browser will be interpreted when complete. Your example is quite clear :
success:function(data) {
var json = data;
$("#commidwin").append(json['msg']);
last_msg_id = json["last_msg_id_db"];
setTimeout("load_msgs()", 1000);
},
jQuery will wait until the response is complete to build your data variable and then will call your success callback.
One way to create long-polling is to have a task and a follower :
the task is the "infinite" loop, it displays nothing but just catch and trigger events, put in a "box".
the follower is an ajax call made every X seconds, it looks inside the "box" filled by the task, and immediately act inside the page.
Here is an example of long-polling, there is no follower, just an event (release) that stops the poll, but you'll get the idea :
<?php
// For this demo
if (file_exists('poll.txt') == false)
{
file_put_contents('poll.txt', '');
}
// If this variable is set, a long-polling is starting...
if (isset($_GET['poll']))
{
// Don't forget to change the default time limit
set_time_limit(120);
date_default_timezone_set('Europe/Paris');
$time = time();
// We loop until you click on the "release" button...
$poll = true;
$number_of_tries = 1;
while ($poll)
{
// Here we simulate a request (last mtime of file could be a creation/update_date field on a base)
clearstatcache();
$mtime = filemtime('poll.txt');
if ($mtime > $time)
{
$result = htmlentities(file_get_contents('poll.txt'));
$poll = false;
}
// Of course, else your polling will kill your resources!
$number_of_tries++;
sleep(1);
}
// Outputs result
echo "Number of tries : {$number_of_tries}<br/>{$result}";
die();
}
// Here we catch the release form
if (isset($_GET['release']))
{
$data = '';
if (isset($_GET['data']))
{
$data = $_GET['data'];
}
file_put_contents('poll.txt', $data);
die();
}
?>
<!-- click this button to begin long-polling -->
<input id="poll" type="button" value="Click me to start polling" />
<br/><br/>
Give me some text here :
<br/>
<input id="data" type="text" />
<br/>
<!-- click this button to release long-polling -->
<input id="release" type="button" value="Click me to release polling" disabled="disabled" />
<br/><br/>
Result after releasing polling :
<div id="result"></div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
// Script to launch polling
$('#poll').click(function() {
$('#poll').attr('disabled', 'disabled');
$('#release').removeAttr('disabled');
$.ajax({
url: 'poll.php',
data: {
poll: 'yes' // sets our $_GET['poll']
},
success: function(data) {
$('#result').html(data);
$('#poll').removeAttr('disabled');
$('#release').attr('disabled', 'disabled');
}
});
});
// Script to release polling
$('#release').click(function() {
$.ajax({
url: 'poll.php',
data: {
release: 'yes', // sets our $_GET['release']
data: $('#data').val() // sets our $_GET['data']
}
});
});
</script>
Demonstration : here.