Displaying progress while waiting for controller in Laravel 4
ajax, laravel, progress
Solution
Well, that's because `{{ Session::get('progess') }}` is only evaluated once, when the page is first rendered. The only way to do what you want is to actually make extra AJAX requests to a different URL that reports the progress. Something like this:
Controller
// Mapped to yoursite.com/progress
public function getProgess() {
return Response::json(array(Session::get('progress')));
}
public function postGenerate() {
// getting values from form (like $record_num)
Session::put('progress', 0);
Session::save(); // Remember to call save()
for ($i = 1; $i < $record_num; $i++) {
$record = new Record();
// adding attributes...
$record->save();
Session::put('progress', $i);
Session::save(); // Remember to call save()
}
$response = Response::make();
$response->header('Content-Type', 'application/json');
return $response;
}
JavaScript
@section('scripts')
<script type="text/javascript">
$(document).ready(function() {
$('#form-overview').on('submit', function() {
setInterval(function(){
$.getJSON('/progress', function(data) {
$('#progress').html(data[0]);
});
}, 1000);
$.post(
$(this).prop('action'),
{"_token": $(this).find('input[name=_token]').val()},
function() {
window.location.href = 'success';
},
'json'
);
return false;
});
});
</script>
@stop
Problem
I've got a form that I want to send by ajax-post to my controller. Meanwhile the HTML is waiting for the generation and saving of the records, I want to display the progress (for now just numbers). I really don't understand why the following code doesn't update `<div id="progress">` with `Session::get('progress')`. Controller: ``` public function postGenerate() { // getting values from form (like $record_num) Session::flash('progress', 0); $i = 1; for ($i; $i < $record_num; $i++) { $record = new Record(); // adding attributes... $record->save; Session::flash('progress', $i); } $response = Response::make(); $response->header('Content-Type', 'application/json'); return $response; } ``` Javascript: ``` @section('scripts') <script type="text/javascript"> $(document).ready(function() { $('#form-overview').on('submit', function() { setInterval(function(){ $('#progress').html( "{{ Session::get('progress') }}" ); }, 1000); $.post( $(this).prop('action'), {"_token": $(this).find('input[name=_token]').val()}, function() { window.location.href = 'success'; }, 'json' ); return false; }); }); </script> @stop ``` HTML: ``` @section('content') {{ Form::open(array('url' => 'code/generate', 'class' => 'form-inline', 'role' => 'form', 'id' => 'form-overview' )) }} <!-- different inputs ... --> {{ Form::submit('Codes generieren', array('class' => 'btn btn-lg btn-success')) }} {{ Form::close() }} <div id="progress">-1</div> @stop ```