How to insert infinite scroll to Laravel Project - laravel

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

Related

Laravel 8 filter data with 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>

autocomplete function not working for mobile view

Hello I am creating searching task in my project it works fine for destop view but when i open my website in mobile and press key then keypad is open and close within second what is problem in my code. What is mistake? why code is not working in mobile view?
//html
<form class="ps-search--header" action="#" method="post">
{{ csrf_field()}}
<input class="form-control" type="text" placeholder="Search Product…" id="product_name">
<button><i class="ps-icon-search"></i></button>
<div id="product_list"></div>
</form>
//controller
public function fetch(Request $request)
{
if($request->get('query'))
{
$query = $request->get('query');
$data = DB::table('products')
->where('product_name', 'LIKE', "%{$query}%")
->get();
$output = '<ul class="dropdown-menu" style=" display:block; ;width:100%">';
foreach($data as $row)
{
$name=[];
$name=explode(" ",$row->product_name);
$output .= '
<li>'.$row->product_name.'</li>
';
}
$output .= '</ul>';
echo $output;
}
}
//autocomplete
$('#product_name').keyup(function(){
var query = $(this).val();
if(query != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url:"/autocomplete",
method:"get",
data:{query:query, _token:_token},
success:function(data){
$('#product_name').fadeIn();
$('#product_list').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#product_name').val($(this).text());
$('#product_list').fadeOut();
});
This kind of keyup wold not work sometimes with mobile which work great on desktop
You can use this Keyup on Your autocomplete function its work on both check the code bellow
$('#product_name').on('keyup input', function(e){
if(e.keyCode == 13) {
$("input").blur();
}
var query = $(this).val();
if(query != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url:"/autocomplete",
method:"get",
data:{query:query, _token:_token},
success:function(data){
$('#product_name').fadeIn();
$('#product_list').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#product_name').val($(this).text());
$('#product_list').fadeOut();
});

ajax is not able to call the function of codeigniter

This is Welcome controller method
public function send_otp()
{
echo 'in';
die;
$phone = $_POST['mobile'];
if ($phone != '') {
$mobile_detail = $this->welcome_model->check_if_already_mobile_no($phone);
if (!empty($mobile_detail)) {
if ($mobile_detail['is_verified'] == 'yes') {
$message = 'Already Verified.';
echo json_encode(array('status' => 'error', 'message' => $message));
exit;
} else {
$this->welcome_model->delete_mobile_no($phone);
}
}
$otp = self::generateRandomNo();
$this->welcome_model->insert_mobile_detail($phone, $otp);
$link = file_get_contents("http://49.50.67.32/smsapi/httpapi.jsp?username=aplusv&password=aplusv1&from=APLUSV&to=$phone&text=$otp&coding=0");
$status = '';
if ($link != '') {
$status = 'success';
$message = 'Successfully Otp send to your no.';
} else {
$status = 'error';
$message = 'Error in sending OTP.';
}
echo json_encode(array('status' => $status, 'message' => $message));
exit;
}
}
This is model
public function check_if_already_mobile_no($mobile_no = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no));
return $query->row_array();
}
public function get_mobile_details($mobile_no = null, $otp = null)
{
$query = $this->db->get_where('mobile_sms', array('mobile_no' => $mobile_no, 'otp' => $otp));
return $query->row_array();
}
public function insert_mobile_detail($phone, $otp)
{
$this->mobile_no = $phone;
$this->otp = $otp;
$this->is_verified = 'no';
$this->created_at = date('Y-m-d H:i:s');
$this->db->insert('mobile_sms', $this);
}
This is view
<div class="container" style="margin-top: 25px;">
<div class="row">
<div class="col-md-12" id="response_msg"></div>
<div class="col-md-4" id="enter_mobile">
<form method="POST" action="#">
<div class="form-group">
<label for="phone">Phone </label>
<input type="text" class="form-control" id="mobile" name="phone" placeholder="Enter Mobile">
</div>
<button type="button" name="send_mobile" id="send_otp" class="btn btn-primary">Submit</button>
</form>
</div>
<script src="assets/js/jquery.js"></script>
<script type="text/javascript">
// var base_url = "<?php echo base_url();?>";
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>
$(function () { // start of doc ready.
$("#send_otp").on('click', function (e) {
var mobile = $('#mobile').val();
alert(mobile);
$.ajax({
url: '<?php echo site_url('index.php/welcome/send_otp'); ?>',
data: {'mobile': mobile},
type: "post",
dataType: 'json',
success: function (data) {
if (data.status == 'success') {
$('#response_msg').html('<div class="alert alert-success" role="alert">' + data.message + '</div>');
$('#mobile_no').val(mobile);
$('#enter_mobile').hide();
$('#verify_otp_form').show();
} else {
$('#response_msg').html('<div class="alert alert-danger" role="alert">' + data.message + '</div>');
}
}
});
});
in ajax is not getting call ie $.ajax is not working here and my controller ie welcome with method send_otp is not called here.
why my function in controller is not getting called
how to solve the issue
what is the proper way to call the controller function using base_url
i have check the console also it is not showing any error
I noticed that you are using site_url() slightly incorrectly: don't write index.php there, just use site_url('welcome/send_otp')
Don't forget you have an unconditional die() at the top of your send_otp method - it will prevent any code below itself from executing

Display Remove and Edit Item button in Order summary in Onepage Checkout page Magento2

I want to display remove and Edit Icon in order summary section in checkout page, I have tried below changes:
/magento_demo/vendor/magento/module-checkout/view/frontend/web/template/summary/item/details.html
I have added Edit / Delete links like this:
<div class="primary">
<a data-bind="attr: {href: getConfigUrl($parent.item_id),title: $t('Edit item')}" class="action edit">
<span data-bind="i18n: 'Edit'"></span>
</a>
</div>
<div class="secondary">
<a href="#" data-bind="attr: {'data-post': getDataPost($parent.item_id),title: $t('Delete item')}" class="action delete">
<span data-bind="i18n: 'Remove'"></span>
</a>
</div>
In
/magento_demo/vendor/magento/module-checkout/view/frontend/web/js/view/summary/item/details.js
I have done below changes:
define(
[
'uiComponent',
'mage/url',
'Magento_Customer/js/customer-data',
'jquery',
'ko',
'underscore',
'sidebar',
'mage/translate'
],
function (Component,url,customerData,$,ko, _) {
"use strict";
return Component.extend({
defaults: {
template: 'Magento_Checkout/summary/item/details'
},
getValue: function(quoteItem) {
var itemId = elem.data('cart-item'),
itemQty = elem.data('item-qty');
return quoteItem.name;
},
getDataPost: function(itemId) {
console.log(itemId);
var itemsData = window.checkoutConfig.quoteItemData;
var obj = {};
var obj = {
data: {}
};
itemsData.forEach(function (item) {
if(item.item_id == itemId) {
var mainlinkUrl = url.build('checkout/cart/delete/');
var baseUrl = url.build('checkout/cart/');
console.log(mainlinkUrl);
obj.action = mainlinkUrl;
obj.data.id= item.item_id;
obj.data.uenc = btoa(baseUrl);
}
});
return JSON.stringify(obj);
},
getConfigUrl: function(itemId) {
var itemsData = window.checkoutConfig.quoteItemData;
var configUrl = null;
var mainlinkUrl = url.build('checkout/cart/configure');
var linkUrl;
itemsData.forEach(function (item) {
var itm_id = item.item_id;
var product_id = item.product.entity_id;
if(item.item_id == itemId) {
linkUrl = mainlinkUrl+"/id/"+itm_id+"/product_id/"+product_id;
}
});
if(linkUrl != null) {
return linkUrl;
}
else {
return '';
}
}
});
}
);
But when I click on delete button, it just redirecting to cart page but not deleting product, what can be the issue here.

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