I am trying to put this into ajax so everytime a person clicks a button in jquery, it creates a php session. Is it possible just using this?
var milisec=00;
var seconds=60;
function display(){
if (milisec<=0){
milisec=9
seconds-=1
}
if (seconds<=-1){
milisec=0
seconds+=1
}
else {
milisec-=1
document.getElementById('counter').innerHTML= seconds+":"+"0"+milisec+"s";
setTimeout(display,100)
}
if (seconds < 10) {
document.getElementById('counter').innerHTML= "0"+seconds+":"+"0"+milisec+"s";
}
}
display()
I need to post the time it took for them to get to the next page using Php sessions, using ajax.
var seconds = 60;
var milisec = 0;
var stop_counter = false;
function display(){
if(milisec == 0)
seconds = seconds - 1;
milisec = milisec - 1;
if(milisec == -1)
milisec = 10;
$('#counter').html((seconds < 10 ? "0" : "") + seconds + ":0" +milisec+ "s");
if( (seconds == 0 && milisec == 0 && stop_counter == true) == false )
setTimeout(function(){ display(); }, 100);
}
$(document).ready(function(){
display();
$('#button').click(function(){
$.post('myphpfile.php', {time : $('#counter').text()}, function(data){
alert('Data from myphpfile.php: ' + data);
stop_counter = true; //stop counter now
});
});
});
myphpfile.php
echo 'you clicked button when counter was ' . $_POST['time'];
//you can do any php stuff here
this code should do what you want but I did not test it.
function $.post() from jQuery library will pass your data to php script and also can retrieve some data which you can display on your site or something.
btw, one second has 1000 miliseconds, not 100
sorry for my english
Yes you can do it by passing the value of "seconds" and "milisec" in the ajax call by
$(document).ready(function(){
$('#button').click(function(){
$.post('session_file.php', {secs : seconds,millisecs:milisec}, function(data){
});
});
});
So in the session_file.php you can write the values of the variables of secs and millisecs in a session
Related
Consider it as the user will login and only giving 45 minutes. How to call a PHP function which is log-out when the Jquery timer runs to 0.
Here's my Code
<script type="text/javascript">
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(minutes + ":" + seconds);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
jQuery(function ($) {
var FortyMinutes = 60 * 45,
display = $('#time');
startTimer(FortyMinutes, display);
});
</script>
And here's my php function
public function logout() {
session_destroy();
redirect('Authentication');
}
You will have to make a request to a new page.
Since PHP is a server side language you will have to go to another page to run any PHP code. This can be done by having a logout.php file:
<?php
logout();
public function logout() {
session_destroy();
redirect('Authentication');
}
?>
On the client side you can make an ajax request to that page. Run the following code after the timer is up.
$.ajax({
type: "GET",
url: 'logout.php',
success: function(data){
alert('Logging you out');
}
});
I am trying to update on screen without refresh the current percentage that is updated into a database when the user checks something but failed to accomplish this.
Problem is that in the console I get the error TypeError: a is undefined ..."resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b
and the GET request is repeated infinite. Within the get request, the response is:
{"percentage":null}. An additional problem is that the GET request seams to load complete (like getting the final response) only when the php script finishes.
I checked the database and every time I refresh the database dynamically I can see the percentage updating. So it's not a problem from the PHP or SQL, may be a problem from getter.php (file that is printing the result) and the json script.
Please help me on this issue I checked the entire day + yesterday on how to echo value from database live and tried lots of examples but did not understood complete how to do it (this is mostly related to jquery knob, want to implement it there after success). Your help is much appreciated.
Jquery:
jQuery_1_11_0('#check').on('submit', function (e) {
done();
function done() {
setTimeout(function () {
updates();
done();
}, 1000);
}
function updates() {
$.getJSON("lib/getter.php", function (data) {
$("#progressbar").empty();
$.each(data.result, function () {
percentage = this['percentage'];
if (percentage = null) {
percentage = 100;
$("#progressbar").html(percentage);
}
});
});
}
});
process.php
$urlsarray = array('google.com', 'yahoo.com', 'bing.com');
// this is a dynamic array created by the user, I am giving just a simple example
$counter = 0;
$total = count($urls1);
$session_id = rand(100000000000000, 999999999999999);
$db->query("INSERT INTO sessions (session_id, percentage) VALUES ('$session_id', '$counter')");
foreach ($urlsarray as $urls) {
doing some things
$counter++;
$percentage = ($counter/$total) * 100;
$db->query("UPDATE sessions SET percentage = '$percentage' WHERE session_id = '$session_id'");
}
$db->query("DELETE FROM sessions WHERE session_id = '$session_id'");
$percentage = 100;
getter.php
include("process.php");
global $session_id;
$readpercentage = $db->query("SELECT percentage FROM sessions WHERE session_id = '$session_id'");
$percentage = $readpercentage->fetch_assoc();
echo json_encode(array('percentage' => $percentage));
ob_flush();
flush();
EDIT 2 UPDATE
function updates() {
$.getJSON("lib/getter.html", function (data) {
$("#progressbar").empty();
$("#progressbar").html(data.percentage);
});
}
EDIT 3
var myInterval = setInterval(function(){ updates(); }, 1000);
function updates() {
$.getJSON("lib/getter.html", function (data) {
//$("#progressbar").empty();
console.log(data);
$("#progressbar").html(data.percentage);
if(data.percentage >= 100){
clearInterval(myInterval);
}
});
}
EDIT 4. changed getter.php
include("process.php");
//global $session_id;
//echo $session_id;
$readpercentage = $db->query("SELECT percentage FROM sessions WHERE session_id = '$session_id'");
$percentage = $readpercentage->fetch_assoc();
$percentage = (int) $percentage['percentage'];
if ($percentage = 100) {
$percentage = 100;
}
echo json_encode(array('percentage' => $percentage));
ob_flush();
flush();
and the js script
var jQuery_1_11_0 = $.noConflict(true);
jQuery_1_11_0('#check').on('submit', function (e) {
var myInterval = setInterval(function(){ updates(); }, 1000);
function updates() {
$.getJSON("lib/getter.html", function (data) {
var percentage = data.percentage;
$("#progressbar").html(percentage).show();
if(percentage >= 100 || typeof percentage !== 'undefined'){
clearInterval(myInterval);
}
});
}
});
// second script is for posting the result
jQuery_1_11_0('#check').on('submit', function (e) {
var validatef = $("#url").val();
var validaterror = $('#errorvalidate');
if (validatef == 'Enter Domains Separated By New Line -MAX 100 DOMAINS-') {
validaterror.text('Please enter domain names in the text area');
e.preventDefault();
} else {
validaterror.text('');
$.ajax({
type: 'post',
url: 'lib/process.php',
data: $('#check').serialize(),
success: function (data) {
$("#result").html(data); // apple
// $("#progressbar").knob().hide();
}
});
e.preventDefault();
} // ending the else
});
I cant help but wonder:
done();
function done() {
setTimeout(function () {
updates();
done();
}, 1000);
}
How does this recursion stops? Because to me it seems like this timeout will keep on firing eternally. You really need a timeInterval here, set it to a variable, and clear the interval when 100% has been reached.
Maybe replace the above with:
var myInterval = setInterval(function(){
updates();
}, 1000);
then, on the updates function
if(percentage >= 100){
clearInterval(myInterval);
}
By the way, doing:
if(percentage = null){
...
}
Did you mean to compare using = instead of == ? If you want to verify that percentage is set and is a valid number, it would probably be a good idea to do:
if(typeof percentage !== 'undefined' && !isNaN(parseFloat(percentage)){
...
}
Look at what you're sending back to your JS code from PHP:
echo json_encode(array('percentage' => $percentage));
Literally that'll be
{"percentage":42}
In your JS code, you then have:
$.getJSON("lib/getter.php", function (data) {
^^^^---the data coming back from PHP
....
$.each(data.result, function () {
^^^^^^---since when did you put a "result" key into your array?
For this JS code to work, you'd have to be doing
echo json_encode(array('result' => $percentage));
^^^^^^---note the new key.
And note that since you're sending back a SINGLE object in the JSON, with a single key:value pair, there is literally no point in using your inner $.each() loop. You could just as well have
$("#progressbar").html(data.percentage);
Ok so I am creating a radio player and basically I need the Title, Content div, Next show Div to refresh at certain times for example 9am then 12pm. I have the JQuery code to refresh the page at a certain time but that isn't quite what I'm after. Any ideas?
Code:
function refreshAt(hours, minutes, seconds) {
var now = new Date();
var then = new Date();
if(now.getHours() > hours ||
(now.getHours() == hours && now.getMinutes() > minutes) ||
now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >= seconds) {
then.setDate(now.getDate() + 1);
}
then.setHours(hours);
then.setMinutes(minutes);
then.setSeconds(seconds);
var timeout = (then.getTime() - now.getTime());
setTimeout(function() { window.location.reload(true); }, timeout);
}
Then I just call the refreshAt function by inserting the following on my page
<script type="text/javascript">refreshAt(04,30,0);</script> //page refreshes at 4:30am.
So this refreshes the Whole page. I just need to refresh the Title, and 2 divs.
What do I need to add/change in the code.
This will call your current URL after interval elapse and reset your title and your div content.
You have to write something like this:
function refreshAt(hours, minutes, seconds) {
var now = new Date();
var then = new Date();
if(now.getHours() > hours || (now.getHours() == hours && now.getMinutes() > minutes) || now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >= seconds) {
then.setDate(now.getDate() + 1);
}
then.setHours(hours);
then.setMinutes(minutes);
then.setSeconds(seconds);
var timeout = (then.getTime() - now.getTime());
setTimeout(function() {
$.get( window.location.pathname, function( data ) {
$('title') = $(data).filter('title').text();
$('.DIV_CLASS') = $(data).filter('.DIV_CLASS').html();
alert( "Load was performed." );
});
}, timeout);
}
NOTE: This script use jQuery, so please include latest jQuery library.
You can try this:
setTimeout(function() {
document.title = "new title";
$(".divname").text("new div text");
}, timeout);
Please try below code :
setTimeout(function(){
$('#divid').load("pageurl #divid" >*",function(){
});
}, 6000);
Your div reload after 6 second.
You can take a look at jQuery's load method.
By using is you can load the content of you div.
setTimeout(function() {
$("#youfirstdivid").load("url1");
$("#youseconddivid").load("url2");
$('title').text("new title");
}, timeout);
Don't forgot to wrap your code inside
$(function(){
//you code goes here
});
and if you want to refresh it at some fixed interval then you can use setInterval rather than setTimeout
I have a PHP process which updates files, and writes a status report with each file.
While that is happening, I was hoping to update the user's browser until the final response.
Unless there is a better way, I simply wanted some advice on how to loop infinitely refreshing getJSON() results until the ajax response comes.
What is the best way to do this?
This ended up being the solution I used:
$(document).on('click', "#ss_batch_edit_processing", function (e) {
var ids = get_selected();
var status_location = '<?php echo symbiostock_TMPDIR . '/report.txt' ?>';
if(ids == 0){
return;
}
$('.' + loading_icon_small).show();
var data = {
action: 'ss_professional_ajax',
security: '<?php echo $ajax_nonce; ?>',
reprocessing_action: $('input:radio[name=ss_reprocessing_action]:checked').val(),
ids: ids,
};
var completed = 0;
$.post(ajaxurl, data, function (response) {
$('.' + loading_icon_small).hide();
completed = 1;
});
var get_update = function(){
$.getJSON(status_location, function (data) {
var update = '<ul><li><strong>'+data['title']+'</strong></li><li><strong>Count:</strong> '+data['count']+' / '+data['total']+'</li><li><strong>Last processed</strong>: Image # '+data['last_id']+'</li></ul>';
$('#ss-reprocessing-results').html(update).delay(1000);
});
if(completed == 1){
clearInterval(timed_requests)
return false;
}
};
var interval = 1000; // every 1 second
var timed_requests = setInterval(get_update, interval);
});
Ive got an problem. I have an button that sends an command to an perl script. For 60 seconds the page will just load and load. So i need an countdown to tell the user how much time until the perl script is finished. So i got his javascript from the web that automaticly counts down when the page loads. Is it possible to reverse this?
http://goo.gl/cYdKg
You see what happens, when you don't state your requirements correctly? Two people doing the same wrong thing (bad for us, we did not clarified before, tho).
$.fn.timedDisable = function(time, callback) {
if (time == null) {
time = 5000;
}
var seconds = Math.ceil(time / 1000);
return $(this).each(function() {
$(this).attr('disabled', 'disabled');
var disabledElem = $(this);
var originalText = this.innerHTML;
disabledElem.text( originalText + ' (' + seconds + ')');
var interval = setInterval(function() {
disabledElem.text( originalText + ' (' + --seconds + ')');
if (seconds === 0) {
disabledElem.removeAttr('disabled')
.text(originalText);
clearInterval(interval);
if (typeof callback !== 'undefined')
callback();
}
}, 1000);
});
};
$(function() {
$('#btnContinue').click(function() {
$(this).timedDisable(5000, function() {
window.alert('done');
});
});
});