Laravel 8 filter data with ajax - ajax

I want to filter the data in my table. I have seen many tutorials online but do not understand. I found a tutorial that seemed very complicated to me. I just want to use a controller and view. Constants are used in that tutorial and the filter data is static but I don't want to use it and my filter data is dynamic. Help me out as a newbie.
The code of the tutorial is given here
app/Constants/GlobalConstants
<?php
namespace App\Constants;
class GlobalConstants {
const USER_TYPE_FRONTEND = "frontend";
const USER_TYPE_BACKEND = "backend";
const ALL = 'All';
const LIST_TYPE = [self::USER_TYPE_FRONTEND, self::USER_TYPE_BACKEND];
const LIST_COUNTRIES = ["Canada", "Uganda", "Malaysia", "Finland", "Spain", "Norway"];
const SALARY_RANGE = ['401762', '85295', '287072', '456969', '354165'];
}
App/User
public static function getUsers($search_keyword, $country, $sort_by, $range) {
$users = DB::table('users');
if($search_keyword && !empty($search_keyword)) {
$users->where(function($q) use ($search_keyword) {
$q->where('users.fname', 'like', "%{$search_keyword}%")
->orWhere('users.lname', 'like', "%{$search_keyword}%");
});
}
// Filter By Country
if($country && $country!= GlobalConstants::ALL) {
$users = $users->where('users.country', $country);
}
// Filter By Type
if($sort_by) {
$sort_by = lcfirst($sort_by);
if($sort_by == GlobalConstants::USER_TYPE_FRONTEND) {
$users = $users->where('users.type', $sort_by);
} else if($sort_by == GlobalConstants::USER_TYPE_BACKEND) {
$users = $users->where('users.type', $sort_by);
}
}
// Filter By Salaries
if ($range && $range != GlobalConstants::ALL) {
$users = $users->where('users.salary', $range);
}
return $users->paginate(PER_PAGE_LIMIT);
}
App/Http/Controllers/HomeController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Constants\GlobalConstants;
class HomeController extends Controller
{
public function index() {
$users = User::getUsers('', GlobalConstants::ALL, GlobalConstants::ALL, GlobalConstants::ALL);
return view('home')->with('users', $users);
}
public function getMoreUsers(Request $request) {
$query = $request->search_query;
$country = $request->country;
$sort_by = $request->sort_by;
$range = $request->range;
if($request->ajax()) {
$users = User::getUsers($query, $country, $sort_by, $range);
return view('pages.user_data', compact('users'))->render();
}
}
}
view code
#foreach($users as $key)
<div class="card">
<div class="card-header">
<img src="{{ asset('assets/images/dev.png') }}" alt="" />
</div>
<div class="card-body">
<span class="tag tag-pink">{{ $key->type }}</span>
<hr>
<span class="tag tag-salary">Salary: {{ $key->salary }}</span>
<h4>{{ $key->email }}</h4>
<p>
{{ $key->address }}
</p>
<h4>Country: {{ $key->country }}</h4>
<div class="user">
#php
$user=App\User::find($key->id)
#endphp
<img src="{{ asset('assets/images/user-3.jpg') }}" alt="" />
<div class="key-info">
<h5>{{ $user['fullname'] }}</h5>
<small>{{ date('d.m.Y H:i:s', strtotime($key->created_at)) }}</small>
</div>
</div>
</div>
</div>
#endforeach
<script>
$(document).ready(function() {
$(document).on('click', '.pagination a', function(event) {
event.preventDefault();
var page = $(this).attr('href').split('page=')[1];
getMoreUsers(page);
});
$('#search').on('keyup', function() {
$value = $(this).val();
getMoreUsers(1);
});
$('#country').on('change', function() {
getMoreUsers();
});
$('#sort_by').on('change', function (e) {
getMoreUsers();
});
$('#salary_range').on('change', function (e) {
getMoreUsers();
});
});
function getMoreUsers(page) {
var search = $('#search').val();
// Search on based of country
var selectedCountry = $("#country option:selected").val();
// Search on based of type
var selectedType = $("#sort_by option:selected").val();
// Search on based of salary
var selectedRange = $("#salary_range option:selected").val();
$.ajax({
type: "GET",
data: {
'search_query':search,
'country': selectedCountry,
'sort_by': selectedType,
'range': selectedRange
},
url: "{{ route('users.get-more-users') }}" + "?page=" + page,
success:function(data) {
$('#user_data').html(data);
}
});
}
</script>

public function create(Request $request)
{
$doctors = Doctors::all();
$query = doctors_slots::query();
'services.','consultation.')
// ->get();
if($request->ajax()){
$doctors_slots = $query->where(['doc_id'=>$request->doctors])->get();
return response()->json(compact('doctors_slot'));
}
$doctors_slots = $query->get();
return view('Admin.booking.add_booking',compact('doctors','doctors_slots'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#doctors").on('change', function() {
var doctors = $(this).val();
$.ajax({
url: "{{ route('booking') }}",
type: "GET",
data: {
'doctors': doctors
},
success: function(data) {
var doctors_slots = data.doctors_slots;
var html = '';
if (doctors_slots.length > 0) {
for (let i = 0; i < doctors_slots.length; i++) {
html += '<option value="' + doctors_slots[i][
'available_time_start'
] + '' + doctors_slots[i]['available_time_end'] + '">\
' + doctors_slots[i]['available_time_start'] + ' To\
' + doctors_slots[i]['available_time_end'] + '\
</option>';
}
} else {
html += '<option>No Data Found</option>';
}
$('#option').html(html);
}
});
});
});
</script>

Related

Impossible to upload file with buefy upload

I'm creating a website and now I try to use my upload file system. I test it with postman and it works perfectly. But when I try to use with my website page, it not works.
Backend : I use Lumen
Frontend : I use Buefy
The upload function into UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
public function uploadImageIntoUser(Request $request, $id){
//try{
$user = User::findOrFail($id);
if ($user->id == Auth::id()) {
$url = json_decode($this->uploadImage($request, $id)->getContent(), true);
$newRequest = new Request();
$newRequest->replace(['picture' => $url['data']['image'] ]);
return $this->update($id, $newRequest);
}
return response()->json(['message' => 'You not have the right to do this'], 412);
/*}catch (\Exception $e){
return response()->json(['message' => 'User not found'], 404);
}*/
}
}
The upload function into my Controller.php
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Galerie;
use Illuminate\Support\Str;
class Controller extends BaseController
{
//Upload image
public function uploadImage(Request $request, $id)
{
try{
$this->validate($request, [
'folder' => array(
'required',
'alpha')
]);
$folder = $request->input('folder');
if(strcmp($folder, "user") !== 0 && strcmp($folder, "article") !== 0 && strcmp($folder, "galerie") !== 0){
return response()->json(['message' => 'Incorrect folder name : choose between user, article and galerie'], 409);
}
} catch (\Exception $e) {
return response()->json(['message' => 'Incorrect folder name : only in lowercase'], 409);
}
$response = null;
$user = (object) ['image' => ""];
if ($request->hasFile('image')) {
$original_filename = $request->file('image')->getClientOriginalName();
$original_filename_arr = explode('.', $original_filename);
$file_ext = end($original_filename_arr);
if($folder == 'user'){
$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = './upload/galerie/';
}
$image = time() . '.' . $file_ext;
if ($request->file('image')->move($destination_path, $image)) {
if ($folder == 'user') {
$user->image = '/upload/user/' . $image;
}else if($folder == 'article'){
$user->image = 'upload/article/' . $image;
}else if($folder == 'galerie'){
$user->image = 'upload/galerie/' . $image;
$galerie = new Galerie;
$galerie->id = Str::uuid();
$galerie->url = $user->image;
$galerie->save();
}
return $this->responseRequestSuccess($user);
} else {
return $this->responseRequestError('Cannot upload file');
}
} else {
return $this->responseRequestError('File not found');
}
}
protected function responseRequestSuccess($ret)
{
return response()->json(['status' => 'success', 'data' => $ret], 200)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
protected function responseRequestError($message = 'Bad request', $statusCode = 200)
{
return response()->json(['status' => 'error', 'error' => $message], $statusCode)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
Call my upload system from my profile page (called connexion.vue)
<template>
<section class="section">
<div class="container">
<p id="center-text" class="title">Informations Personnelles</p><br>
<b-notification v-if="error" type="is-warning">
{{ error }}
</b-notification>
<div class="columns">
<div class="column">
<img :src='baseURL + loggedInUser.picture'>
<b-field label="Modifier la photo de profil">
<b-field class="file is-secondary" :class="{'has-name': !!file2}">
<b-upload v-model="file2" class="file-label" rounded>
<span class="file-cta">
<b-icon class="file-icon" icon="upload"></b-icon>
<span class="file-label"><strong>Sélectionner un fichier à envoyer</strong></span>
</span>
<span class="file-name" v-if="file2">
{{ file2.name }}
</span>
</b-upload>
</b-field>
</b-field>
<b-button v-if="file2" type="is-secondary" #click="upload">Envoyer</b-button>
</div>
<div class="column">
<p class="title">{{ loggedInUser.pseudo }} <b-button #click="modifyPseudo" icon-right="pencil"/> </p><br v-if="!isModifyPseudo">
<form v-if="isModifyPseudo" method="post" #submit.prevent="sendModification">
<b-field label="Nouveau nom d'utilisateur" label-for="newPseudo">
<b-input id="newPseudo" v-model="newPseudo"></b-input>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
<p class="subtitle">Adresse mail : {{ loggedInUser.email }} <b-button #click="modifyMail" icon-right="pencil"/> </p>
<form v-if="isModifyMail" method="post" #submit.prevent="sendModification">
<b-field label="Nouvelle adresse mail" label-for="newMail">
<b-input id="newMail" v-model="newMail" type="email"></b-input>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
<p class="subtitle">Nationalité : {{ loggedInUser.nationality }} <b-button #click="modifyNation" icon-right="pencil"/> </p>
<form v-if="isModifyNation" method="post" #submit.prevent="sendModification">
<b-field label="Nouvelle nationalité" label-for="newNation">
<b-select expanded v-model="newNation" icon="earth">
<option
v-for="nation in nationalities"
:value="nation.code"
:key="nation.id">
{{ nation.name }}
</option>
</b-select>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
</div>
</div>
</div>
</section>
</template>
<script>
import { mapGetters } from 'vuex'
import countries from '#/assets/countries.json';
export default {
middleware: 'auth',
computed: {
...mapGetters(['isAuthenticated', 'loggedInUser'])
},
data (){
return {
baseURL: 'http://localhost:8000/',
isModifyPseudo: false,
isModifyMail: false,
isModifyNation: false,
newPseudo: '',
newMail: '',
newNation: '',
nationalities: {},
error: '',
file2 : null,
}
},
methods: {
modifyPseudo() {
if(!this.isModifyPseudo){
this.newPseudo='';
}
this.isModifyPseudo = !this.isModifyPseudo;
},
modifyMail() {
if(!this.isModifyMail){
this.newMail='';
}
this.isModifyMail = !this.isModifyMail;
},
modifyNation() {
if(!this.isModifyNation){
this.newNation='';
}
this.isModifyNation = !this.isModifyNation;
},
async upload(){
try{
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
const newPicture = await this.$axios.post('users/' + this.loggedInUser.id + '/picture', formData, {
headers: {'Content-Type': 'multipart/form-data'}
});
console.log(newPicture);
const updatedUser = {...this.$auth.user}
updatedUser.picture = newPicture.data.picture;
this.$auth.setUser(updatedUser)
this.file2 = null;
}catch (error){
//this.error = error.response.data.message;
console.log(error.response);
}
},
async sendModification(){
try{
if(this.isModifyPseudo){
const newPseudo = await this.$axios.put('users/' + this.loggedInUser.id, {
pseudo: this.newPseudo
});
const updatedUser = {...this.$auth.user}
updatedUser.pseudo = newPseudo.data.pseudo;
this.$auth.setUser(updatedUser)
this.newPseudo = '';
this.isModifyPseudo = false;
}
if(this.isModifyMail){
const newMail = await this.$axios.put('users/' + this.loggedInUser.id, {
email: this.newMail
});
const updatedUser = {...this.$auth.user}
updatedUser.email = newMail.data.email;
this.$auth.setUser(updatedUser)
this.newMail = '';
this.isModifyMail = false;
}
if(this.isModifyNation){
const newNation = await this.$axios.put('users/' + this.loggedInUser.id, {
nationality: this.newNation
});
const updatedUser = {...this.$auth.user}
updatedUser.nationality = newNation.data.nationality;
this.$auth.setUser(updatedUser)
this.newNation = '';
this.isModifyNation = false;
}
}catch(error){
this.error = error.response.data.message;
}
}
},
async mounted() {
try {
this.nationalities = countries;
} catch (err) {
throw err;
}
},
}
</script>
<style scoped>
img {
border-radius: 50%;
object-fit: cover;
height: 10em;
width: 10em;
}
.container #center-text {
text-align: center;
}
.file-label strong{
color: white;
}
</style>
And when I click on the send button, because I don't catch the error, it sends the error 500.
EDIT :
So into my upload function into my profile page (called connexion.vue) :
I replace that
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
by this
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
formData.append('folder', 'user');
and into my Controller.php file I replace this :
if($folder == 'user'){
$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = './upload/galerie/';
}
by this
if($folder == 'user'){
$destination_path = storage_path('../public/upload/user/');
//$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = storage_path('../public/upload/article/');
//$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = storage_path('../public/upload/galerie/');
//$destination_path = './upload/galerie/';
}

How can I fetch autocomplete data into their respected element using Ajax and Laravel?

Here is my problem.
I'm trying to fetch the data from an auto-completing text-box.
There are two text-boxes:
Region and province.
I have successfully fetched the data on the text-box having region as name.
My problem is, it gives the same value to the next text-box having province as name.
In my Laravel blade I have this code:
<input id="region" type="text" class="form-control" name="region" value="" required autofocus>
<div id="regionList"> </div>
<input id="province" type="text" class="form-control" name="province" value="" required autofocus>
<div id="provinceList"> </div>
I have also a javascript file named auto-complete
$(document).ready(function() {
$('#region').keyup(function() {
var region = $(this).val();
if (region != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url: "register/showRegion",
method: "POST",
data: { region: region, _token: _token },
success: function(data)
{
$('#regionList').fadeIn();
$('#regionList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
$('#province').keyup(function() {
var province = $(this).val();
if (province != '')
{
var _prov_token = $('input[name="_token"]').val();
$.ajax({
url: "register/showProvince",
method: "POST",
data: { province: province, _token: _token },
success: function(data)
{
$('#provinceList').fadeIn();
$('#provinceList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
});
And on my routes I included this
Route::post('/register/showRegion', 'LocationController#showRegion');
Route::post('/register/showProvince', 'LocationController#showProvince');
And on my controller is this
public function index() {
return view('auth.register');
}
function showRegion(Request $request)
{
if ($request->get('region'))
{
$region = $request->get('region');
$regions = Refregion::where('regDesc', 'LIKE', "$region%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($regions as $region)
{
$output .= '<li>'.$region->regDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
function showProvince(Request $request)
{
if ($request->get('province'))
{
$province = $request->get('province');
$province = Refprovince::where('provDesc', 'LIKE', "province%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($provinces as $province)
{
$output .= '<li>'.$province->provDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
I'm trying to figure out why it gives the same value to the other text-box "province" when I have selected region.
Can someone help me with this, or at least explain to me why this happen?
Thank you
change it
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
on this
$('#regionList').on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
and change it
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
on this
$('#provinceList').on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});

Search results to show in blade using ajax and laravel

I have a search place for costumers to search the product which will be displayed in blade. I am using ajax and laravel. Here is my code as much as I wrote. The query works well and when I print $filter I can see the results.
$('.gotosearch').on('click' , function() {
var search = $(this).val()
var inpvalue = $('.form-control').val()
$.ajax({
url:'/searchproducts',
type:'post',
data: {
inpvalue,
"_token" : token
},
success:function(r) {
console.log(r)
}
})
})
Route::post('/searchproducts' , 'ProductController#searchproducts');
function searchproducts(Request $search) {
$filter = ProductModel::where('Product_Name','LIKE', $search->inpvalue.'%')->get();
}
You can use response()->json in you controller
As per Laravel documentation
The json method will automatically set the Content-Type header to
application/json, as well as convert the given array to JSON using the
json_encode PHP function:
return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]);
Try this:
return response()->json($filters->toArray());
https://laravel.com/docs/5.8/responses#json-responses
try this:
// search text
<div class="form-group">
<input type="text" id="search" name="search" class="form-control" id="exampleInputEmail" aria-describedby="emailHelp" placeholder="Search" value="{{ old('accountNo') }}" style="font-size:20px;font-weight:bold;" required>
</div
// search result
<div id="getResult" class="panel panel-default" style="width:400px; height: 150px; overflow-y:auto; position:absolute; left:50px; top:180px; z-index:1; display:none;background-color:white">
<div id="getList"></div>
</div>
//ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#search').keyup(function(){
var search = $('#search').val();
if(search==""){
$('#getResult').css('display', 'none').hide();
}
else{
var getQueries = "";
$.get("{{ url('/') }}" + '/search/' + search,
{search:search},
function(data){
if(data){
$('#getResult').css('display', 'block');
}else{
$('#getResult').css('display', 'none')
}
if(search == ''){
$('#getResult').css('display', 'none').hide();
}else{
$.each(data, function (index, value){
var id=value.ID;
getQueries += '<ul style="margin-top:3px; list-style-type:none;">';
getQueries += '<a href={{ url("add-contribution-amount")}}' +'/'+ value.id + '>' + value.fullname +' | '+value.accountno + '</a>';
getQueries += '</ul>';
});
$('#getList').html(getQueries );
}
})
}
});
</script>
//controller
public function CustomerSearch($getSearch){
$search = $getSearch;
$members = DB::table('tblcustomers')
->where('accountno', 'like', "%$search%")
->select('id','branchID', 'fullname', 'savingstype', 'accountno')
->orderby('id','asc')
->get();
return $members;
}
//route
Route::get('/search/{searchQuerys?}', 'ContributionController#CustomerSearch');

How to insert infinite scroll to Laravel Project

Am very new to Jquery and Ajax being used in laravel and been trying to implement infinite scroll to my project and i have no idea where to start
The Controller:
$books= DB::table('books')->where('status', 'post')->orderBy('created_at', 'DESC')->paginate(15);
if ($books->isEmpty())
{
$books= null;
return view('landingpage')->withBooks($books);
}
return view('landingpage')->withBooks($books);
The view
#if ($books== null)
<center><p class="paragraph"> Be the first to share your shopping experience here</p></center>
#else
<div class="row mt-0"> <div class="infinite-scroll"> #foreach ($books as $item)
<div class="col-lg-4 mt-3">
<p class="paragraph"> <sup><i class="fa fa-quote-left" style="font-size:5px" aria-hidden="true"></i></sup>{{$item->title}}<sup><i class="fa fa-quote-right" style="font-size:5px" aria-hidden="true"></i></sup> </p>
<img src="../images/{{$item->rate}}.png" style="width:50%" alt="Image">
<h2 style="font-size:18px">{{$item->firstname}} {{$item->lastname}}</h2> </div>#endforeach </div>{{$books->links()}}</div>
#endif
The JS
<script type="text/javascript">
$('ul.pagination').hide();
$(function() {
$('.infinite-scroll').jscroll({
autoTrigger: true,
loadingHtml: '<img class="center-block" src="images/loading.gif" alt="Loading..." />',
padding: 0,
nextSelector: '.pagination li.active + li a',
contentSelector: 'div.infinite-scroll',
callback: function() {
$('ul.pagination').remove();
}
});
});
Any help will be grately appreciated
I use ajax for infinate scroll this is example :
Method for view :
public function index(){
return view('index');
}
Method for get data wia ajax:
public function ajaxData(Request $request)
{
$post_query = Trends::query()
->where('is_offer', '!=', 1)
->where('direct_to', null)
->orderBy('id', 'desc')
->paginate(12);
$data['post_list'] = $post_query;
if ($data['post_list']->count() > 0) {
$ajax_data['post'] = true;
$ajax_data['next_url'] = $data['post_list']->nextPageUrl();
$ajax_data['next_data'] = $data['post_list'];
} else {
$ajax_data['html'] = false;
$ajax_data['post'] = false;
$ajax_data['next_url'] = $data['post_list']->nextPageUrl();
}
return response()->json($ajax_data);
}
And this is my script in blade
var loaddataUrl = '{!! route('explore-ajax-data',array_merge(request()->all())) !!}';
var nextData = true;
$(document.body).on('touchmove', onExploreScroll); // for mobile
$(window).on('scroll', onExploreScroll);
function onExploreScroll() {
if ($(window).scrollTop() >= ($(document).height() - $(window).height()) * 0.9) {
if (nextData) {
nextData = false;
loadMoreData();
}
}
}
function loadMoreData() {
$.ajax({
type: 'GET',
url: loaddataUrl,
success: function (data) {
if (data.next_url) {
loaddataUrl = data.next_url;
console.log(data.next_data);
nextData = true;
} else {
nextData = false;
}
},
error: function (data) {
nextData = true;
}
})
}
route(explore-ajax-data) map to public function ajaxData(Request $request)
my routes are :
// this will display home page or home view
Route::get('home', 'HomeController#index')->name('home');
// this is for ajax request.
Route::get('ajax/explore-data', 'HomeController#ajaxData')->name('explore-ajax-data');
link of tutorial

Displaying progress while waiting for controller in Laravel 4

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
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

Resources