Form Progressbar + PHP Session variable updating progress

Form Progressbar + PHP Session variable updating progress

Hey everyone.

I just wanna share an idea that I have after some research for a simple and functional way to do update a progress bar using the $_SESSION variable of PHP.

Yes, I know most people uses some file written by the PHP with the data, but this way is faster and wont consume many resources.

In this example, given a Form with two Inputs (From and To).
From [number]
To [number]
These values will be poster by $.post() function to the Load.php file so it will do a loop (FOR) for every number between them until it reaches it.

HTML / JQuery Progress bar
  1. <form id="someForm" name="someForm" method="post" action="load.php">
  2. <p>From <input type="text" name="from" id="from" value="0" /> To <input type="text" name="to" id="to" value="100000" /></p>
  3. <p><button name="btnSubmit" type="submit" id="btnSubmit">Calculate</button></p>
  4. </form>

  5. <div id="progress"></div>

  6. <script>
  7.       $('#someForm').on('submit',function(){
  8.             $.post($(this).attr('action'), $(this).serialize()); //send the form
  9.             return false; //prevent the form for submiting or redirecting
  10.       });

  11.       setInterval(      function(){
  12.             $.getJSON('status.php', function(data) {
  13.                   $('#progress').progressbar({value: data});
  14.                   }
  15.             )},2000);
  16. </script>
Now there will be 2 PHP files:

  1. $from = $_POST['from'];
  2. $to = $_POST['to'];

  3. // this file will load the form data. I use a loop, due that what Im developing is an questionary, so it has to load a lot of questions, answers, options,...

  4. for($i = $from; $i <= $to; $i++)
  5. {
  6.       session_start(); // Start the session when using it. Not before or out of the loop. Remember that you are only using it to store the % of progress.

  7.       //      ... do some stuff
  8.       // Save data, process the $_POST data, etc.
  9.       // ...

  10.       $Status = round($i * 100 / $to); // determine the % of completion / load
  11.       $_SESSION['status'] = $Status;
  12.       session_write_close();          //THIS is the most important part. This function will close the session writting. Why? Because if the script loop is still running, the $_SESSION will be unaccesible and you have to wait till it ends to access it.
  14. //      sleep(1);
  15. // added to recreate the loading process.
  16. }

  1. session_start();
  2. $Status = $_SESSION["status"];
  3. header('Content-type: application/json');
  4. echo json_encode($Status);

So, what you guys think? Is a good idea or will be better to write the progress to a file?

Let me know your thoughts.