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
- <form id="someForm" name="someForm" method="post" action="load.php">
- <p>From <input type="text" name="from" id="from" value="0" /> To <input type="text" name="to" id="to" value="100000" /></p>
- <p><button name="btnSubmit" type="submit" id="btnSubmit">Calculate</button></p>
- </form>
-
- <div id="progress"></div>
-
- <script>
- $('#someForm').on('submit',function(){
- $.post($(this).attr('action'), $(this).serialize()); //send the form
- return false; //prevent the form for submiting or redirecting
- });
-
- setInterval( function(){
- $.getJSON('status.php', function(data) {
- $('#progress').progressbar({value: data});
- }
- )},2000);
- </script>
Now there will be 2 PHP files:
load.php
- $from = $_POST['from'];
- $to = $_POST['to'];
-
- // 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,...
-
- for($i = $from; $i <= $to; $i++)
- {
- 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.
-
- // ... do some stuff
- // Save data, process the $_POST data, etc.
- // ...
-
- $Status = round($i * 100 / $to); // determine the % of completion / load
- $_SESSION['status'] = $Status;
- 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.
-
- // sleep(1);
- // added to recreate the loading process.
- }
status.php
- session_start();
- $Status = $_SESSION["status"];
- header('Content-type: application/json');
- 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.