talkhabi
talkhabi

Reputation: 2759

PHP responding to ajax when running process

I'm trying to get some data from Ajax request when already PHP running a long script ;

but when the Ajax has been answered that script in PHP is completed, and I need to get Ajax response during running other scripts .

JS

setInterval(function(){
    $.post( 'progress.php','',
    function(data){
        $('.-info-').html(data);
    }); 
},100);

progress.php

session_start();
echo $_SESSION['progress'].'%';

running.php

session_start();
$i=0;
while($i<99){
    $i++;
    $_SESSION['progress'] = $i;
    //sleep(1);
    //flush();
}

Is there any way to response when "while" is running?

Upvotes: 0

Views: 410

Answers (4)

Shadar
Shadar

Reputation: 22

You can use a global var but the better in mind is make a static or singleton class

class counter {
  private $_progress=0;

  public static function doProgress() {
    $i=0;
    while($i<99){
    $i++;
    $this->_progress = $i;
    }
  }

  public static function getProgress() {
    return $this->_progress;
  }

so in progress.php do

 echo Counter::getProgress()

and in you javascript you must use setinterval() function in my mermory to call at intervaled time the process.php script

Upvotes: 0

Vasiliy vvscode Vanchuk
Vasiliy vvscode Vanchuk

Reputation: 7159

use flush() to send output to browser and onreadystatechange to get response at client side

$i=0;
while($i<99){
    $i++;
    echo $i; 
    flush();
    sleep(1);
}

an onreadystatechange will be call on every portion of wata from your script ( http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp )

you should check state 3 - State 3 LOADING Downloading; responseText holds partial data. so you easily can use it - you can check it here developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

Upvotes: 1

dognose
dognose

Reputation: 20889

Edit: Marc B is right. The session will be locked and not updated as required. So you need to store the progress in an system you can access asynchronously from multiple connections - maybe the database?

running.php:

session_start();
$i=0;
while($i<99){
    $i++;
    // Store progress in Database
}

progress.php:

 session_start();
 //read progress from Database

Upvotes: 1

Marc B
Marc B

Reputation: 360632

PHP doesn't dump out a copy of the saved session data every time you update $_SESSION. The session file is actually LOCKED by PHP when any particular process is using it.

You'd need to do:

while($i<99){
    session_start();  // start session
    $i++;
    $_SESSION['progress'] = $i;

    session_write_close();  // save session data, release session file lock

    sleep(...);
}

In other words, your code would never work, as your running script would keep the session open/locked, preventing progress from ever accessing it.

Upvotes: 1

Related Questions