I'm trying to make a progress bar that fill in real time. I've tried to adapt this example to my laravel project but probably I missed something.
My html code and javascript code:
<div style="border:1px solid black;width:500px;height:80px">
<div class="bar" style="background-color:green;height:inherit;width:0px"></div>
</div>
<p id="progress"></p>
<button onclick="longJob()" type="button">long job</button>
<button onclick="getProgress()" type="button">progreso</button>
<script type="text/javascript">
function longJob(){
$.ajax({
url: "/longJob",
type: "POST",
success: function (response) {
$('.bar').css('width', '250px');
}
})
}
function getProgress(){
$.ajax({
url: "/getProgress",
type: "POST",
success: function (response) {
var progress = response['progress'];
$('#progress').text(progress);
if(progress < 10){
getProgress();
}
}
})
}
getProgress();
</script>
And my php functions:
public function longJob(){
for($i=1;$i<=10;$i++){
Session::set('progress', $i);
sleep(1);
}
return response()->json([
'success' => 'true'
]);
}
public function getProgress(){
$progress = Session::get('progress');
return response()->json([
'progress' => $progress
]);
}
When I load my page the function getProgress() starts to run over and over, retrieving '0'. When I click on the button for long job getProgress() stops for 10 seconds until longJob finishes and then retrieves progress of 10.