I'm new to php and I want to control a php while loop script, using buttons (start/stop), the start button make an ajax call to the start.php script that define $_SESSION['loop'] = TRUE and execute the loop, the stop button make an ajax call to the stop.php script that just change $_SESSION['loop'] to FALSE.
Below is my code so far, but when I hit the stop button I became the alert (success stop) only after the while loop finish looping, which mean the loop didn't break as I was assuming.
I think it's something with the session that is locked while the loop is executing. If so, how to change the $_SESSION['loop'] value and make the loop read that value each time?
index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#start').click(function(){
$.ajax({
url: "start.php"
});
});
$('#stop').click(function(){
$.ajax({
url: "stop.php",
success: function(){
alert('success stop');
},
error: function(){
alert('failure stop');
}
});
});
});
</script>
<button id="start">Start</button>
<button id="stop">Stop</button>
start.php
<?php
session_start();
$_SESSION['loop'] = TRUE;
ini_set('max_execution_time', 300);
$i = 0;
while($i < 100) {
if ($_SESSION['loop'] == TRUE) {
//query to save some variables
// Pause 10s after saving 2
if ($i != 0 && $i%2 == 0) {
sleep(10);
}
$i++;
} else {
break;
}
}
?>
stop.php
<?php
session_start();
if(isset($_SESSION['loop'])) {
$_SESSION['loop'] = FALSE;
}
?>
Your start and stop operations are in two different sessions, so changing $SESSION in one makes no difference to the other.
I think, you should use multi-threading for doing such things.
Please take some time to read it:
"Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time."
http://php.net/manual/en/function.session-write-close.php
Hence, it appears that $_SESSION['loop'] is written to session file at the end.
If you want to explicitly write data to session file, add session_write_close after $_SESSION['loop'] = TRUE. Note, if you need to read/write some session data again in the same script, you need to start the session and then read/write data.
Related
These codes work but when I click somewhere (link or button), redirected to logout.php
var s= 0;
jQuery(function(){
jQuery(window).bind('beforeunload', function () {
if (s == 0) {
$.ajax({
async: false,
url: 'logout.php'
});
}
s++;
});
});
You could put in your session a variable with time() inside and use it as a short expiry limit, and while the user is inside your page do continous ajax calls to a php that updates the expiry. At the top of your page put:
session_start();
if(isset($_SESSION['expiry']))
if(time() > $_SESSION['expiry']){
session_destroy();
header("Refresh:0");
die();
}
$_SESSION['expiry'] = time()+20;
keep_alive.php
session_start();
$_SESSION['expiry'] = time()+20;
And in your js ping keep_alive.php with ajax every 10 seconds. If the user closes the page and doesen't rapidly reopen it loses his session
little issue over here.
I have a php function that is called via AJAX and looks like this:
function processActiveDirectory(){
$var = new GetLDAPUsers;
echo "Getting Users from Active Directory.... <br />";
$adusers = $var->getAllUsers();
echo "setting up images.... <br />";
// processing more stuff
echo "finished";
}
I'm trying to get a "live- log" echo. Meaning before every step the echo should output to a Log area, one step after another. So the user knows what's going on.
But the Problem is, that the log doesn't appear during the process, it just fills in at the whole text at the end of the process. Everything else works fine. The Log just doesn't appear at runtime, but after the function is finished it appears at the right position.
My AJAX call:
jQuery(document).ready(function($) {
$('#lii-form').submit(function() {
data = {
action: 'lii_map_images'
};
$.post(ajaxurl, data, function(response){
$('#lii_log').html(response);
});
return false;
});
});
This is how it's build:
Edit
Other than in this thread I'm already using an ajax call, to call the function. It's within the called function that I'm echoing stuff...
Edit 2
I'm using wordpress
Sorry I can't offer more informations, because of enterprise restrictments.
This is a short over-view on your need. Please develop further with this idea.
This uses two AJAX calling - one for the main process and other for progress:
Script:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
//Start the main process
$.ajax({
url: 'main.php',
success: function(data) {
}
});
function getProgress(){
$.ajax({
url: 'progress.php',
success: function(data) {
$("#progress").html(data);
if(data != "finished"){
getProgress();
}
}
});
}
//Start the progress section
getProgress();
</script>
<div id="progress"></div>
main.php
<?php
$arr = ['Getting Users from Active Directory....','setting up images....','finished'];
foreach($arr as $value) {
session_start();
$_SESSION["progress"]=$value;
session_write_close();
sleep(1);
}
progress.php
<?php
session_start();
sleep(1);
echo $_SESSION["progress"];
So your processActiveDirectory will come under Main.php and echo should be replaced with SESSION variable
I think there is no need in such thing as LOG process WITH AJAX. AJAX is too heavy thing and it could be a bad design if you want it. It's better to use web sockets or not use at all
Session is client side staff, but is it possible through clear it using javascript code?
I would like too have the idea like this and ,can it convert to jquery format? Thank you.
js
$(function(){
$("#closeTab").click(function() {
window.parent.$('#tt').tabs('close','Create List');
$.post("clear.php",function(data){
});
});
});
php
<?
if (isset($_SESSION['lname']))
unset($_SESSION['lname']);
if (isset($_POST['creminder']))
unset($_SESSION['creminder']);
?>
Is this one ok ?
make an ajax call to the server and let your server page kills/ends the session
HTML
<a href="#" id="aKill" > Kill Session</a>
Script
$(function(){
$("#aKill").click(function(){
$.post("serverpage.php",function(data){
// if you want you can show some message to user here
});
});
and in your serverpage.php, Execute the PHP script to terminate the session.
Create a separate file to clear the session only. clearsession.php
session_start();
session_destroy();
Now, make a simple request
$("#aKill").click(function(){
$.get("clearsession.php");
}
The below covers the basics more or less.
The Function:
function destroySession(){
var theForm = $("#yourForm");
//we don't need any ajax frame.
theForm.each(function(){ this.reset() });
$.ajax({
url: 'destroysession.php',
type: 'post',
data: 'sure=1', //send a value to make sure we want to destroy it.
success: function(data);
alert(data);
}
});
}
The PHP (destroysession.php):
<?php
//whatever logic is necessary
if(!empty($_POST['sure'])){
$sure = $_POST['sure'];
if($sure == 1){
//logic to destroy session
echo 'Session Destroyed!';
}else if($sure != 1){
//logic to perform if we're being injected.
echo 'That value is incorrect. What are you doing over there?';
}
}else{
//logic to perform if we're being injected.
echo 'That value is incorrect. What are you doing over there?';
}
?>
The HTML:
<input type='button' value='reset' onclick='destroySession()'>
I'd like to have a jQuery progress bar that updates based on the status of the server side request. I'm basing this code off of this tutorial but it uses a file uploader as its base (same as this question). I can't get it to work quite the same without the file uploader. The problem is that the progress bar only updates after process.php is done. Rather than asynchronously asking for an update on the progress, it waits for the whole process to be done. I only see the data: data alert once.
Any ideas?
Webpage:
<form id="upload-form" action='process.php' method="post" target="upload-frame">
<input type="hidden" id="uid" name="UPLOAD_IDENTIFIER" value="<?php echo $uid; ?>" >
<input type="submit" value="Submit" />
</form>
<div id="progressbar"></div>
<iframe id="upload-frame" name="upload-frame" style="display:none"></iframe>
Process.php - called when form is submitted
<?php
session_start();
$varArray=array(1,2,3,4);
$_SESSION['total']=count($varArray);
foreach($varArray as $val){
$_SESSION['current']=$val;
sleep(2);
}
?>
javascript
$(document).ready(function() {
var started = false;// This flag determines if the upload has started
$(function() {
// Start progress tracking when the form is submitted
$('#upload-form').submit(function() {
$('#progressbar').progressbar();// Initialize the jQuery UI plugin
// We know the upload is complete when the frame loads
$('#upload-frame').load(function() {
// This is to prevent infinite loop
// in case the upload is too fast
started = true;
// Do whatever you want when upload is complete
alert('Upload Complete!');
});
// Start updating progress after a 1 second delay
setTimeout(function() {
// We pass the upload identifier to our function
updateProgress($('#uid').val());
}, 1000);
});
});
function updateProgress(id) {
var time = new Date().getTime();
// Make a GET request to the server
// Pass our upload identifier as a parameter
// Also pass current time to prevent caching
$.ajax({
url: 'getProgress.php',
type: "GET",
cache: false,
data: {'uid':id},
dataType: 'text',
success: function(data){
alert("data: " + data);
var progress = parseInt(data, 10);
if (progress < 100 || !started) {
// Determine if upload has started
started = progress < 100;
// If we aren't done or started, update again
updateProgress(id);
}
// Update the progress bar percentage
// But only if we have started
started && $('#progressbar').progressbar('value', progress);
}
});
}
}(jQuery));
getProgress.php - called by the ajax request:
<?php
session_start();
if (isset($_REQUEST['uid'])) {
if (isset($_SESSION['total']) && isset($_SESSION['current'])) {
// Fetch the upload progress data
$total = $_SESSION['total'];
$current = $_SESSION['current'];
// Calculate the current percentage
$percent_done = round($current/$total*100);
echo $percent_done;
}else{
echo 100;// If there is no data, assume it's done
}
}
?>
AFAIK, PHP sessions are actually synchronous. That means that the Process.php script is blocking the getProgress.php script from running until Process.php is done with the session.
So what happens is:
Process.php starts and calls session_start ()
The server gives session control to session_start ()
getProcess.php starts and calls session_start ()
The server blocks getProcess.php until the session is unused.
Process.php completes and closes the session.
The server resumes getProcess.php and gives it control over the session.
getProcess.php now sees that the process is complete.
See http://www.php.net/manual/en/function.session-write-close.php.
Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. [...]
I haven't tested the following code since I don't have access to a server at the moment but I imagine somethin like it should work:
<?php
$varArray=array(1,2,3,4);
session_start();
$_SESSION['total']=count($varArray);
session_write_close ();
foreach($varArray as $val){
session_start();
$_SESSION['current']=$val;
session_write_close ();
sleep(2);
}
?>
How can we call Php functions with in the JavaScript If-else condition.
For Example,
if (top == self) {
// not in any kind of frame
} else {
// in a frame
// calling php function
}
</script>
Here, PHP exit() function calling for both if and else conditions. I need to call that function for only in else part.
Please advise me.
Thanks.
Prabhu
Technically not possible. However you can make an AJAX call to a PHP page and get the values returned by it.
PHP (test.php):
<?php
$x = 10;
$y = 20;
$val = $y / $x;
echo $val;
?>
Javascript (jQuery):
$(document).ready(function() {
$.ajax({url: 'test.php',
type: 'POST',
success: function(data){
//takes the value returned by test.php and
//puts it directly into the element with
//id = someElement
$('#someElement').html(data);
}
});
As far as calling exit(); and making the page that holds the JavaScript stop processing, you just can't unless you control the logic on that same page in PHP and call exit(); from there.
Do not try to mix javascript with php.
If you want to stop the page from loading you could also redirect the page to an other (php) page where you simply put exit();
If this javascript is in a function just use : return; or return false;