AngularJS pagination with laravel model - pagination bar is not displayed properly - php

Here is my AngularJS code for building the pagination with angular bootstrap pagination:
$scope.employees = [],
$scope.currentPage = 0,
$scope.numPerPage = 2,
$scope.totalItems = '',
$scope.maxSize = 2;
$scope.getEmployee = function (offset) {
$http.get('/employee/'+offset).then(function (response) {
$scope.employees = response.data.data;
$scope.totalItems= response.data.totalRows;
console.log($scope.totalItems);
});
};
$scope.getEmployee(0);
$scope.getPage = function () {
$scope.getEmployee($scope.currentPage === 1 ? 0 : $scope.currentPage);
};
Trying to list 2 employees per page (Now i have 6 rows in mysql query)
Laravel controller
public function getTotalEmployees($offset)
{
$result = Company::limit(2)->offset($offset)->get();
return response()->json(array('data'=>$result,'totalRows'=>Company::count()));
}
query will give correct output but the paginationbar is not properly displayed.
HTML
<ul>
<li ng-repeat="emp in employees">{{emp.name}}</li>
</ul>
<pagination
ng-model="currentPage"
total-items="20"
max-size="maxSize"
boundary-links="true"
ng-change="getPage()">
</pagination>
I think its the problem with totalItems value but i can't fixed it here is screenshot of the pagination bar
I can't select the next and previous buttons its disabled

Somethink like this. I'm not that familiar with laravel but it should work with mini modifications for you. I added an other controller action in laravel which return you the total count of your items. This API endpoint is called on this.$onInit which is a methods available since AngularJS 1.5. It will be called when the controller is initialized. Here is a simple fiddle demo with an pagination example.
AngularJS controller
$scope.employees = [],
$scope.currentPage = 0,
$scope.numPerPage = 2,
$scope.totalItems = 0,
$scope.maxSize = 2;
this.$onInit = function () {
$scope.getEmployee();
$http.get('/employee/getTotalCount').then(function (response) {
$scope.totalItems = response.data.count;
});
};
$scope.getEmployee = function () {
$http.get('/employee/getItems/'+ ($scope.currentPage * $scope.numPerPage) +'/' + $scope.numPerPage).then(function (response) {
$scope.employees = response.data.data;
});
};
$scope.getPage = function () {
$scope.getEmployee();
};
Laravel controller
public function getTotalCount()
{
$companies = Company::all();
return response()->json('count' => $companies->count());
}
public function getItems($offset, $limit)
{
$result = Company::limit($limit)->offset($offset)->get();
return response()->json(array('data'=>$result));
}

Related

Append select2 multiple in laravel vuejs

Im having a trouble on how can I append data in select2, currently I can only manage to display the first item list of my cities based on the province selected. I've been using onchange to trigger the function. It would be great if anybody could figure out, thanks in advance!.
data(){
provinces: [],
cities: [],
brgys: []
}
mounted() {
this.ini();
},
methods:{
ini(){
$('#kt_select_province').on('change', () => {
let id = $('#kt_select_province').val();
id = id.map(i=>Number(i));
this.provinces.map(i=> {
if (id.indexOf(i.id) != -1) {
i.active="true";
} else{
i.active="false";
}
});
if(id.length != 0) {
this.getCity(id); //called city function
}
});
getCity(id) {
axios.get(BASE_URL + "/api/city/" + id).then(response => {
this.cities = response.data; // did not append here
this.cities.map(i=>i.active="false")
});
},
}
cityController.php
public function show($id)
{
return response()->json(City::whereIn('province_id', [$id])->get());
}

Laravel Ajax Pagination: No request

I have some difficulties with my ajax pagination linked to a filter. Here's how it should work. The user can access via a specific page to a form. When clicking the submit button, a raw sql request is made in JS and a POST ajax request is achieved to get the results at the bottom of the page with a pagination menu. This part works. But I have some issues with the pagination menu because the links don't work. For example, by clicking the "page 2" link, nothing happens.
Here are the different parts of my code:
Routes
Route::get('articles/filter', 'ArticleController#filterx');
Route::post('articles/request/ajax/articles/filter', 'ArticleController#filtery');
Route::get('articles/request/ajax/articles/filter', 'ArticleController#filtery');
Controller
ArticleController
public function filterx() { // get filter page
return view('filter');
}
public function filtery(Request $request) { // filter ajax function
$articles = Article::paginate(2);
if($request->ajax()) {
// partial view returned in html
return $html = view('filterResults', compact('articles'));
}
}
Views
filter.blade.php
#extends('layouts/app')
#section('title')
Title
#endsection
#section('content')
<div class="container">
<!-- filter -->
<h2>Filter</h2>
<div class="content-card content">
<form method="POST" action="">
<!-- form code... -->
</form>
</div>
<div id="filter-results">
</div>
</div>
#endsection
filterResults.blade.php
#foreach($articles as $article)
<p>{{ $article->name }}</p>
#endforeach
{{ $articles->links() }}
Javascript
$("#submit-button").click(function(e) {
e.preventDefault();
// ajax request (raw mysql request)
var requestQuery = ...; // (quite long) raw request
console.log(requestQuery); // console verification of request
$.ajax({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
url: '../articles/request/ajax/articles/filter',
type: 'POST',
data: {
request: requestQuery
},
success: function(html) {
$("#filter-results").empty().html(html);
}
});
});
$(window).on('hashchange', function() {
// if hash in url
if (window.location.hash) {
// page contains hash value
var page = window.location.hash.replace('#', '');
if (page == Number.NaN || page <= 0) {
return false;
}
// if ok ->getData returned
else {
getData(page);
}
}
});
$(document).on('click', '.pagination a', function(e) {
e.preventDefault();
$('.pagination li').removeClass('active');
$(this).parent('li').addClass('active');
var url = $(this).attr('href');
var page = $(this).attr('href').split('page=')[1];
getData(page,url);
});
function getData(page,url) {
$.ajax(
{
url: url,
type: 'get',
datatype: 'html',
done: function(data) {
console.log('ok');
$('#filter-results').empty().html(data);
location.hash = page;
},
fail: function(jqXHR, ajaxOptions, thrownError) {
console.log('No response from server');
}
});
}
I don't understand why it is not working, I thing I misunderstood something.
Thanks and have a good day
Laravel uses the page value from the request, or query string, by convention. If you choose not to use that, you can set your own. If following convention, you'd need to append the query string page=# to your url in the ajax request.
The fourth argument of the Builder::paginate is the page number:
public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
{
$page = $page ?: Paginator::resolveCurrentPage($pageName);
$perPage = $perPage ?: $this->model->getPerPage();
$results = ($total = $this->toBase()->getCountForPagination())
? $this->forPage($page, $perPage)->get($columns)
: $this->model->newCollection();
return $this->paginator($results, $total, $perPage, $page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => $pageName,
]);
}
You could also define your own page resolver. The default is set in PaginationServiceProvider:
Paginator::currentPageResolver(function ($pageName = 'page') {
$page = $this->app['request']->input($pageName);
if (filter_var($page, FILTER_VALIDATE_INT) !== false && (int) $page >= 1) {
return (int) $page;
}
return 1;
});
Route::get('articles/filter/{page}', 'ArticleController#filter');
public function filter(Request $request, int $page) {
$articles = Article::paginate($page);
}
it's all

Infinite Scrolling of dynamic data with ionic 1 and angular js 1

How can I do infinite scrolling in ionic 1 and angular js 1 with dynamic data (Http request)from database ?
HTML :
<ion-view view-title="Playlists">
<ion-content>
<ion-list>
<ion-item class="item-avatar" ng-repeat="item in items">
<h2>{{item.name}} -{{item.id}}</h2>
<p>{{item.iso_code_2}} {{item.iso_code_3}}</p>
</ion-item>
</ion-list>
<div ng-if="hasData">
<ion-infinite-scroll on-infinite="loadMore()" distance="5%">
</ion-infinite-scroll>
</div>
</ion-content>
</ion-view>
Controller.js
This is my angularjs controller. Use a factory named 'CountryService' which is doing http call to get server data. In formdata = {limit:serviceconfig.showlimit,page:page}; I sent limit =10 where I set in config.js service,and set page =1 for the first time.
For the first time GetDefault is called after scrolling GetLoadMore will be called with page =2 and limit=10 with next 10 new data.
angular.module('starter.usercontroller', [])
.controller('UserCtrl', function($scope, CountryService, $ionicModal,
$timeout, $http, serviceconfig, $ionicPopup,$state, ionicDatePicker, $filter) {
$scope.hasData=1; // If data found
$scope.items = [];
CountryService.GetDefault().then(function(items){
$scope.items = items;
});
$scope.loadMore = function() {
CountryService.GetLoadMore().then(function(items){
$scope.items = $scope.items.concat(items);
if(items.length>0)
{
$scope.$broadcast('scroll.infiniteScrollComplete'); // If has data then load more
}
else
{
$scope.hasData=0; // If no more data to load
}
});
};
})
.factory('CountryService',
['$http','serviceconfig',function($http,serviceconfig){
var items = [];
var page =1;
var formdata = {limit:serviceconfig.showlimit,page:page};
return {
GetDefault: function(){
formdata = {limit:serviceconfig.showlimit,page:page};
return $http.post(serviceconfig.serviceUrl+ "all-countries",formdata).then(function(response){
if(response.data.status==1)
{
items = response.data.countries;
}
else
{
items =[];
}
return items;
});
},
GetLoadMore: function(){
formdata = {limit:serviceconfig.showlimit,page:page};
return $http.post(serviceconfig.serviceUrl+ "all-countries",formdata).then(function(response){
page = page+1;
if(response.data.status==1)
{
items = response.data.countries;
}
else
{
items =[];
}
return items;
});
}
}
}]);
Config.js For configuration
In this config.js I set the server url and limit, how many data I want to fetch from server each scroll. 'configService' service I inject in my js controller.
angular.module('starter.configService', [])
.service('serviceconfig',function(){
this.serviceUrl='http://192.168.1.116/ionicserver/service/';
this.showlimit=10;
})
PHP SERVER SITE CODE:
I am using php laravel 5.1. So this is my php controller function for getting county list by below function
public function postAllCountries() // Countries
{
$data = Request::all();
$limit= $data['limit'];
$page = $data['page'];
$offset = ($page - 1) * $limit;
$countries = Country::where('id','>',0)->take($limit)->skip($offset);
$countries = $countries->get()->toArray();
if(!empty($countries))
{
echo json_encode(array('status'=>1,'msg'=>'Successfully Registered','countries'=>$countries));
}
else
{
echo json_encode(array('status'=>0,'msg'=>'No data found'));
}
exit;
}

Select2 load data from database - CodeIgniter

I try to load database data in my Select2 input. (Im working on CI)
Here's my code from the controller : transforms array in echo json
class Ajax extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('client');
}
public function returnClientsAjax(){
echo json_encode($this->client->getClients());
}
}
Model : returning an array of results
function getClients(){
return $this->db->query("SELECT idclient AS id, CONCAT(societe,' [', nom,']') as text FROM du_client WHERE (societe != '' AND nom != '') AND evo2012 >=2 AND type_client != 'Particulier' AND statut_client = 'Demandeur' AND idclient = 6141;")->result_array();
}
My Select2 :
$("#sel_clients").select2({
placeholder: "Search for an Item",
ajax: {
dataType: "json",
url: "http://commexpert.dev.local/ajax/returnclientsajax",
results: function (data) {
return {results: data};
}
}
});
The input still empty so, don't know what to do.
Thnaks :D
I think something is missing on your data results method. Here is my code from working ajax select2 component:
results: function (data) {
var results = [];
var id1 = data.id;
var name = data.text;
$.each(data.data, function(index, item){
results.push({
id: item[id1],
text: item[name].trim()+' : '+ item[id1]
});
});
return {results: results};
}
also, I'm having somewhat diff data call also:
data: function (term) {
try {
mirko = $(this).closest('[rendered]').find( "input[fparamname$=" + $(this).attr('flookupfiltref') + "]" ).val();
if (mirko.indexOf(' : ') >=0 ) { // pocetna vrijednost
mirko = mirko.split(' : ')[1].trim();
}
} catch(e){
mirko = '';
}
return {
sp_name: $(this).attr('objectname'),
fl_name: $(this).attr('fparamname'),
node_id: $(this).attr('node_id'),
bound: mirko,
q: term,
};
},
I'm having somekind of manipulation before sending or returning q to server,, but I hope that can help you for your service :)
hth, k

Search for a table within a database in Laravel 4 PHP Framework

I am trying to set up search for a table within database in mine within the Laravel 4 PHP Framework. I am using jquery to accomplish this. I have a table "artists", that I am trying to allow a user to search through. I have a model "Artist.php", and a controller "SearchController.php" that I am using to control the logic. Finally, I have a view "search.blade.php" that I am using as the user facing file. Here is the relevant code:
SearchController.php:
public function show_search() {
$limit = 10;
if(isset($_GET['mode']) && !empty($_GET['mode'])) {
switch($_GET['mode']) {
case 'autocomplete':
if(isset($_GET['keywords']) && !empty($_GET['keywords'])) {
$query = htmlspecialchars($_GET['keywords']);
$query = mysql_real_escape_string($query);
$results = Artist::search_artists($query);
$data = array();
$i = 0;
if(isset($results) && !empty($results)) {
foreach($results as $result) {
if (strlen(strstr($result->stage_name, 'artists')) == 0) {
if($i < $limit) {
$data[$i] = $result;
$i++;
}
}
}
}
exit;
}
break;
}
}
return View::make('search.search');
}
Artist.php:
public static function search_artists($query) {
$search_artists = DB::table('artists')
->where('artists.stage_name', 'LIKE', $query)
->orderBy('created_at', 'DESC')
->get();
return $search_artists;
}
search.blade.php:
<input type="text" class="search" id="inputSearch" /><br />
<div id="divResult"></div>
<script type="text/javascript">
$(function(){
$(".search").keyup(function() {
var inputSearch = $(this).val();
var data = {mode : 'autocomplete', keywords : inputSearch};
if(inputSearch!='') {
$.ajax({
type: "GET",
url: "/search/search",
data: data,
cache: false,
success: function(html) {
console.log(html);
$("#divResult").html(html).show();
}
});
}
return false;
});
});
</script>
I call all of this with the route:
Route::get('/search/search', array('uses' => 'SearchController#show_search'));
When I run this and I type things into the search box, I see in the javascript console it reads:
event.returnValue is deprecated. Please use the standard event.preventDefault() instead.
and the results don't display under the search box. Any idea what could be going wrong? Thank you for your help.
The javascript warning is caused by your return false;. If you need it (doesn't seem necessary for the keyup event unless you want to catch the enter key), you should do something like:
$(".search").keyup(function(e) {
e.preventDefault(); // prevent the default action of the event
I am not familiar with Laravel, but it seems to me that you are not getting any results because you are not doing anything with the $data variable in your controller.
I would guess you need something similar to:
return View::make('search.search', $data);
to pass the variable to your view.

Categories