Laravel 5 Paginate + Infinite Scroll jQuery - javascript

I am trying to use paginate() to achieve infinite scroll. I think the easiest way is using the 'infinite-scroll' to achieve this. If you have any other suggestion how to do it without infinite-scroll library, just using jQuery, I'd be happy to know..
I am returning the variable to view like this:
public function index()
{
$posts = Post::with('status' == 'verified')
->paginate(30);
return view ('show')->with(compact('posts'));
}
My View:
<div id="content" class="col-md-10">
#foreach (array_chunk($posts->all(), 3) as $row)
<div class="post row">
#foreach($row as $post)
<div class="item col-md-4">
<!-- SHOW POST -->
</div>
#endforeach
</div>
#endforeach
{!! $posts->render() !!}
</div>
Javascript Part:
$(document).ready(function() {
(function() {
var loading_options = {
finishedMsg: "<div class='end-msg'>End of content!</div>",
msgText: "<div class='center'>Loading news items...</div>",
img: "/assets/img/ajax-loader.gif"
};
$('#content').infinitescroll({
loading: loading_options,
navSelector: "ul.pagination",
nextSelector: "ul.pagination li:last a", // is this where it's failing?
itemSelector: "#content div.item"
});
});
});
However, this doesn't work. The ->render() part is working because I am getting [<[1]2]3]>] part. However, the infinite scroll doesn't work. I also don't get any errors in the console.
[<[1]2]3]>] is like this in the view:source:
<ul class="pagination">
<li class="disabled"><span>«</span> </li> // «
<li class="active"><span>1</span></li> // 1
<li>2</li> // 2
<li>3</li> // 3
<li>»</li> // »
</ul>

Easy and helpful is this tutorial - http://laraget.com/blog/implementing-infinite-scroll-pagination-using-laravel-and-jscroll
Final script could looks like this one
{!! HTML::script('assets/js/jscroll.js') !!}
<script>
$('.link-pagination').hide();
$(function () {
$('.infinite-scroll').jscroll({
autoTrigger: true,
loadingHtml: '<img class="center-block" src="/imgs/icons/loading.gif" alt="Loading..." />', // MAKE SURE THAT YOU PUT THE CORRECT IMG PATH
padding: 0,
nextSelector: '.pagination li.active + li a',
contentSelector: 'div.infinite-scroll',
callback: function() {
$('.link-pagination').remove();
}
});
});
</script>
You just need to use laravel's pagination
{!! $restaurants->links() !!}

You should be able to use the Pagination just fine as long as your call to get new posts is different than page load. So you'd have two Laravel calls:
1.) To provide the template of the page (including jQuery, CSS, and your max_page count variable -- view HTML)
2.) For the AJAX to call posts based on the page you give it.
This is how I got my infinity scroll to work...
HTML:
<!-- Your code hasn't changed-->
<div id="content" class="col-md-10">
#foreach (array_chunk($posts->all(), 3) as $row)
<div class="post row">
#foreach($row as $post)
<div class="item col-md-4">
<!-- SHOW POST -->
</div>
#endforeach
</div>
#endforeach
{!! $posts->render() !!}
</div>
<!-- Holds your page information!! -->
<input type="hidden" id="page" value="1" />
<input type="hidden" id="max_page" value="<?php echo $max_page ?>" />
<!-- Your End of page message. Hidden by default -->
<div id="end_of_page" class="center">
<hr/>
<span>You've reached the end of the feed.</span>
</div>
On page load, you will fill in the max_page variable (so do something like this: ceil(Post::with('status' == 'verified')->count() / 30);.
Next, your jQuery:
var outerPane = $('#content'),
didScroll = false;
$(window).scroll(function() { //watches scroll of the window
didScroll = true;
});
//Sets an interval so your window.scroll event doesn't fire constantly. This waits for the user to stop scrolling for not even a second and then fires the pageCountUpdate function (and then the getPost function)
setInterval(function() {
if (didScroll){
didScroll = false;
if(($(document).height()-$(window).height())-$(window).scrollTop() < 10){
pageCountUpdate();
}
}
}, 250);
//This function runs when user scrolls. It will call the new posts if the max_page isn't met and will fade in/fade out the end of page message
function pageCountUpdate(){
var page = parseInt($('#page').val());
var max_page = parseInt($('#max_page').val());
if(page < max_page){
$('#page').val(page+1);
getPosts();
$('#end_of_page').hide();
} else {
$('#end_of_page').fadeIn();
}
}
//Ajax call to get your new posts
function getPosts(){
$.ajax({
type: "POST",
url: "/load", // whatever your URL is
data: { page: page },
beforeSend: function(){ //This is your loading message ADD AN ID
$('#content').append("<div id='loading' class='center'>Loading news items...</div>");
},
complete: function(){ //remove the loading message
$('#loading').remove
},
success: function(html) { // success! YAY!! Add HTML to content container
$('#content').append(html);
}
});
} //end of getPosts function
There ya go! That's all. I was using Masonry with this code also so the animation worked wonderfully.

Related

How to pass a value form db to popup windows

I want to pass value to popup windows by using a tag with href when I click a
get values form db into hidden layer how to passing values by js.
A tag code
<a 'href=index.php?id=3'></a>
Hidden layer
<div class='wrap'>
<div class='content'>
<h2>Well Hello!</h2>
<p>
<? if ( isset($_GET['id'])){
$id = $_GET['id'];
echo $id ;} ?>
</p>
</div>
</div>
js code
$('a').on('click', function(){
$('.wrap, a').toggleClass('active');
return false;
});
If you want to do this the javascript way, see this example.
$(document).ready(function() {
$('a.toggle-wrap').on('click', function(e) {
e.preventDefault(); // prevent default behaviour of the link that would reload the page
$('.wrap, a.toggle-wrap').removeClass('active'); // remove class active on every link clicking
var target_id = $(this).attr("data-id"); //get the desired id from link
var wrap_element = $('.wrap[data-target=' + target_id + '] p');
var link_element = $('a[data-id=' + target_id + ']');
link_element.toggleClass('active');
$.ajax({
type: "GET",
url: "someOtherScriptThatOnlyOutputsResults.php",
data: "id="+target_id,
success: function(resultData) {
wrap_element.html(resultData).toggleClass('active'); // only toggle desired ids
}, error: function() {
wrap_element.html('Could not load data').toggleClass('active');
}
});
});
});
.wrap {
display: none;
}
.wrap.active {
display: block;
}
a {
color: green;
}
a.active {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="toggle-wrap" data-id="3">Link 3</a>
<a class="toggle-wrap" data-id="4">Link 4</a>
<div class="wrap" data-target="3">
<div class="content">
<h2>Well Hello content 3!</h2>
<p>Your db content related to id 3 from database, using php.
</p>
</div>
</div>
<div class="wrap" data-target="4">
<div class="content">
<h2>Well Hello content 4!</h2>
<p>Your db content related to id 4 from database, using php.
</p>
</div>
</div>
Add identifiers to the hidden wrap(s) and the link(s) and work with those. By using queries as seen in the js snippet, you can target certain HTML tags. Use CSS display to hide and show your wrap tag.
Create a new PHP file someOtherScriptThatOnlyOutputsResults.php to get and return data:
<?php
if(isset($_GET['id'])) {
$pdo = new PDO('mysql:host=someHost;dbname=someDatabase', 'someUser', 'somePass');
$statement = $pdo->prepare("SELECT columnWithContent FROM yourContentTable WHERE id = ?");
$statement->execute(array($_GET['id']));
$row = $statement->fetch();
$content = $row['columnWithContent'];
echo $content;
}
?>

how can i convert this code from hover to either click or toggle

Below is the script works fine with hover but need it to be either a toggle or a click function if anyone has any ideas on how to achieve this.
it collects data from different php files depending on the button that is hoverd over thats fine but when working on the page it pops up all the time kind of annoying
<script type="text/javascript">
$(document).ready(function(){
$(".container").hide();
$(['btn1', 'btn2', 'btn3']).each(function(){
var btn = this;
var con = $("#"+btn).children('.container');
$("#"+btn).hover(
function(){
$(".hover").mouseout();
$(this).addClass('hover');
var cache = $(con).children('p');
//check to see if content was loaded previously
if(cache.size()){
con.show();
}else{
$(con).show();
$(con).html('<img src="imgs/loader.gif" alt="Loading..." />');
$.ajax({
url: 'data/'+btn+'.php',
type: 'get',
success: function(data){
$(con).html(data);
}
});
}
},
//mouseout
function(){
if($.browser.msie){
$(con).hide();
}else{
$(con).fadeOut(250);
}
$(this).removeClass('hover');
}
);
});
});
</script>
<div id="btn1" class="wrapper">
<div class="button">
<p><i class="fa fa-users" aria-hidden="true"></i></p>
</div>
<div class="content">
</div>
</div>
<div id="btn2" class="wrapper">
<div class="button">
<p><i class="fa fa-comments" aria-hidden="true"></i></p>
</div>
<div class="content">
</div>
</div>
Thanks guys i figured out how to do this and also make the coding less.
so what it does is you create the dropdown button with the btn1 id
and the next button with id of btn2.
the parsing php files called btn1.php you code what you need to display the data in the content div of the buttons
Aaaargh sorry seems like only the first button works shows the conent div and closes when clicked but subsequent new buttons show the content div Ajax requests are all fine
but dont close when clicked again
<script>
$(".wrapper").click( function()
{
var btn = $(this).attr('id');
var conte = $('.content').css('display');
var con = $(this).children('.content');
if (conte == 'block') {
$(con).css('display','none');
} else if (conte == 'none') {
$(con).css('display','block');
$(con).html('<img src="imgs/loader.gif" alt="Loading..." />');
$.ajax({
url: 'configuration/'+btn+'.php',
type: 'get',
success: function(data){
$(con).html(data);
}
});
}
});
</script>

Ajax setInterval is executed twice for manipulated notification

First, Let's me explain. I have a page to monitoring my users. In this page, I can see all the request of my users on a table and I can see too the total of the request is in to the server. My question is, How can I make a notification when a new request is come. I want to make a notification like big window pop-up said "New Request Is Come" and one tone of music that will be play.
This is my code :
Main page
<!-- start: Header -->
<div class="container-fluid-full">
<div class="row-fluid">
<noscript>
<div class="alert alert-block span12">
<h4 class="alert-heading">Warning!</h4>
<p>You need to have JavaScript enabled to use this site.</p>
</div>
</noscript>
<!-- start: Content -->
<!--First indicator-->
<marquee>Belum Diterima: <span id="request_belum_terima"><?php
if ($request_belum_terima > 0) {
echo $request_belum_terima;
} else {
echo "0 ";
};
?></span> buah Request</marquee>
<div class="box-header">
<h2><i class="halflings-icon align-justify"></i><span class="break"></span>Penerimaan Request</h2>
<div class="box-icon">
<i class="halflings-icon chevron-up"></i>
</div>
</div>
<!--Table one-->
<div class="box-content" id="things_table">
<?php $this->load->view('view_monitoring_belum_terima'); ?>
</div>
<!--Second indicator-->
<marquee>Belum Selesai: <span><?php
if ($request_sudah_terima > 0) {
echo $request_sudah_terima;
} else {
echo '0 ';
}
?></span> Request</marquee>
<div class="box-header">
<h2><i class="halflings-icon align-justify"></i><span class="break"></span>Outstanding Request</h2>
<div class="box-icon">
<i class="halflings-icon chevron-up"></i>
</div>
</div>
<!--Table two-->
<div class="box-content" id="things_table2">
<?php $this->load->view('view_monitoring_belum_selesai'); ?>
</div>
</div><!--/.fluid-container-->
</div><!--/row-->
<?php $this->load->view('view_monitoring_modal') ?>
<div class="clearfix"></div>
<!-- start: JavaScript-->
<?php $this->load->view('/include/js.html'); ?>
<!-- end: JavaScript-->
<?php $this->load->view('view_monitoring_js'); ?>
I using codeigniter and some jquery to develop my app. So, I solve it one by one.
First, I use the indicator from first marquee. If you can see, there are one ID's jquery on span tag. For ex, First indicator have value 1. So, I use ajax to pool the data from database and check it with old value;
This is the code :
Controller
public function hitungRequestBelumTerima() {
$row = $this->model_request->hitungRequestBelumTerima();
echo json_encode($row);
}
Model
public function hitungRequestBelumTerima() {
$this->db->select('*');
$this->db->where('is_approved', 1);
$this->db->where('by_who is not null');
$this->db->where('it_person is null');
$query = $this->db->get('tbl_requestfix');
if ($query->num_rows() > 0) {
return $query->num_rows();
}
return NULL;
}
After that, I write a jquery's code to autorefresh the indicator like this :
function refresh() {
var ini;
var requestMasuk = $('#request_belum_terima').text();
setTimeout(function() {
$.ajax({
url: '<?php echo base_url() . 'control_closing/hitungRequestBelumTerima/' ?>',
type: 'POST',
dataType: 'json',
success: function(obj) {
if (obj > requestMasuk) {
ini = obj;
$('#request_belum_terima').text(obj);
alert("New request coming");
}
}
}).always(function() {
$('#request_belum_terima').text(ini);
}).done(function() {
$('#request_belum_terima').text(ini);
});
$('things_table2').fadeOut('slow').load('<?php ?>').fadeIn('slow');
refresh();
}, 20000);
}
$(document).ready(function() {
refresh();
}
It working to refresh, but I dont know, why alert is pop up twice. So, the case is : one new request but two alert of notif has pop-up on one interval. So, in first 10 minutes for ex, Alert is raising. In 20 minutes, alert still coming. But in 30 minute, the alert is not raise. Why the alert raise twice ?
use setInterval instead of setTimeout. Here is your ajax function (ajax not tested, as you say its working)
function refresh() {
var ini;
var requestMasuk = $('#request_belum_terima').text();
$.ajax({
url: '<?php echo base_url() . 'control_closing/hitungRequestBelumTerima/' ?>',
type: 'POST',
dataType: 'json',
success: function(obj) {
if (obj > requestMasuk) {
ini = obj;
$('#request_belum_terima').text(obj);
alert("New request coming");
}
}
}).always(function() {
$('#request_belum_terima').text(ini);
}).done(function() {
$('#request_belum_terima').text(ini);
});
$('things_table2').fadeOut('slow').load('<?php ?>').fadeIn('slow');
}
$(document).ready(function() {
setInterval(function () {
refresh();
}, 20000);
}

Click function does not work even though the CSS selector does

I have a gallery of thumbnails, all with class .thumb that are added by a php code that a friend wrote. I tried to add a simple click function:
$('.thumb').click(function () {
console.log('test');
});
And it does not log anything. I had tried this before we switched to php as well, and it still didn't work. (At that time the images were imported with jQuery)
Below is the relevant html code:
<div id="navbar">
<img src="images/sig.png">
<ul>
<li id="port"><a>Portfolio</a></li>
<ul id="inner">
<?php
$dir = opendir("images/portfolio");
while ($dosya = readdir($dir)){
if(substr($dosya,-1)!="." and is_dir("images/portfolio/".$dosya)){
if(file_get_contents("images/portfolio/".$dosya."/active.dl") == 'active'){
?>
<li class="galleryActivator" cats="<?=$dosya?>"><?=file_get_contents("images/portfolio/".$dosya."/name.dl")?></li>
<?php }}
}?>
</ul>
<li><li>Events</li></li>
<li>About</li>
</ul>
</div>
<div id="main">
<div id="thumbnails">
</div>
</div>
And the script:
(function(){
$('#inner').hide();
$('#main').hide();
$('#slideshow').hide();
$('#port').click(function(){
$('#inner').slideToggle(200);
console.log('test');
});
$('.galleryActivator').click(function () {
$("#main").hide();
$("#main img").remove();
var category = $(this).attr('cats');
var catSrc = "images/portfolio/" + category + "/files/";
var size = $(this).attr("data-size");
console.log(size);
var $thumbnails = $("#thumbnails");
$thumbnails.load( "albumler.php?adres="+category );
$('#main').fadeIn(200);
});
$('.thumb').click(function () {
console.log('test');
});
})();
it seems you are loading your thumbnails dynamically; you should set your event handler like this:
$(document).on("click", ".thumb", function () {
console.log('test');
});
you dont have anything in your above HTML with a class of thumb
but once you do just add document ready
$(document).ready(function(){
$('.thumb').click(function () {
console.log('test');
});
});

Multiple Javascript Functions in Jquery

I've been having the same issue for a very long time and I'm wondering if someone can teach me what I'm doing wrong.
I created a multipage Jquery (like the one in the example below) however, when I go to add a reference to a .js file I've saved it always tends to either not load up the pages content or if positions somewhere else it just simply wont work!
My HTML code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Find A Deal</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<style>
img.fullscreen {
max-height: 100%;
max-width: 100%;
}
</style>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript">
$(document).on('pagebeforeshow', '#index', function(){
$("#list").empty();
var url="http://localhost/tmp/json4.php";
$.getJSON(url,function(json){
//loop through deals
$.each(json.deals,function(i,dat){
$("#list").append("<li><a id='"+dat.dealid+"' data-restaurantid=" + dat.restaurantid + " data-image=" + dat.image + "><h1>"+dat.name+"</h1><h6>"+dat.dname+"</h6><h5>"+dat.description+"</h5></a></li>");
$(document).on('click', '#'+dat.dealid, function(event){
if(event.handled !== true) // This will prevent event triggering more then once
{
dealObject.dealID = $(this).attr('id');
dealObject.restaurantid = $(this).attr('data-restaurantid');
dealObject.shortName = $(this).find('h1').html();
dealObject.image = $(this).attr('data-image');
//dealObject.dname = $(this).find('input').html();
//dealObject.dname = $(this).find('desc').val();
dealObject.dealName = $(this).find('h6').html();
dealObject.description = $(this).find('h5').html();
//dataObject.dname=$(this).find('p').html()
//dealObject.name = $(this).find('desc').eq(0).val(dealObject.name);
$.mobile.changePage( "#index2", { transition: "slide"} );
event.handled = true;
}
});
});
$("#list").listview('refresh');
});
});
$(document).on('pagebeforeshow', '#index2', function(){
//$('#index2 [data-role="content"]').html('You have selected Link' + dealObject.dname);
$('#index2 [data-role="content"]').find('#deal-img').attr('src',dealObject.dealObject);
$('#index2 [data-role="content"]').find('#title').html(dealObject.name);
//$('#index2 [data-role="content"]').find('#description').html(dealObject.dname);
$('#index2 [data-role="content"]').find('input#desc').val(dealObject.description);
$('#index2 [data-role="content"]').find('input#tname').val(dealObject.dealName);
$('#index2 [data-role="content"]').find('input#dealid').val(dealObject.dealID);
});
var dealObject = {
dealID : null,
restaurantid : null,
shortName : null,
image : null,
dealName : null,
description: null
}
</script>
</head>
<body>
<div data-role="page" id="index">
<div data-role="header" data-position="fixed">
<h1>Current Deals</h1>
</div>
<div data-role="content">
<div class="content-primary">
<ul id="list" data-role="listview" data-filter="true"></ul>
</div>
</div>
<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li>Home</li>
<li>My Deals</li>
</ul>
</div>
</div>
</div>
<!--New Page -->
<div data-role="page" id="index2">
<!--<script src="js/ammend.js"></script>--!>
<div data-role="header">
<h1> Find A Deal </h1>
</div>
<div data-role="content">
<!-- <?php
if( !isset( $_SESSION ) ){
session_start();
}
if( isset( $_SESSION['username'] ) ){
echo ".";
} ?> --!>
<form id="test">
<label for="name">Deal Name:</label>
<input type="text" value="" name="tname" id="tname"/>
<label for="desc">Description</label>
<input type="text" value="" name="desc" id="desc"/>
<a data-role="button" id="amend" data-icon="star" data-iconpos="left">Amend Deal </a>
<input type="text" value="" name="dealid" id="dealid"/>
<h3></h3>
<!--<img src="" width="100px" height="100px" id="deal-img">
<h1 id="title"></h1>
<h3 id="description"></h3>
<p id="name"></p>--!>
</div>
<footer data-role="footer" data-position="fixed">
<nav data-role="navbar">
<ul>
<li>Home</li>
<li>My Deals</li>
</ul>
</nav>
</footer>
</div>
</body>
</html>
Apologies if it's hard to read. This javascript function will work just fine by itself. When an item in index is clicked it brings you to a new page in index2. On index 2 there's a submit button to which is connect to a file referenced <script src="js/ammend.js"></script>. This is where things normally seem to go wrong for me as it's like they're cancelling eachother out or just not co-operating together.
The js file at that location is:
$(document).on('pagebeforeshow', '#index2', function(){
$('#amend').on('click', function(){
if($('#tname').val().length > 0 && $('#desc').val().length > 0 && $('#dealid').val().length > 0){
userObject.tname = $('#tname').val(); // Put username into the object
userObject.desc = $('#desc').val(); // Put password into the object
userObject.dealid = $('#dealid').val();
// Convert an userObject to a JSON string representation
var outputJSON = JSON.stringify(userObject);
// Send data to server through ajax call
// action is functionality we want to call and outputJSON is our data
ajax.sendRequest({action : 'index2', outputJSON : outputJSON});
} else {
alert('Please fill all nececery fields');
}
});
});
$(document).on('pagebeforeshow', '#index2', function(){
if(userObject.name.length == 0){ // If username is not set (lets say after force page refresh) get us back to the login page
$.mobile.changePage( "#index2", { transition: "slide"} ); // In case result is true change page to Index
}
$(this).find('[data-role="content"] h3').append('Deal Amended:' + userObject.name); // Change header with added message
//$("#index").trigger('pagecreate');
});
// This will be an ajax function set
var ajax = {
sendRequest:function(save_data){
$.ajax({url: 'http://localhost/test/login/amend.php',
data: save_data,
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (num) {
if(num == "true") {
$.mobile.changePage( "#index", { transition: "slide"} ); // In case result is true change page to Index
} else {
alert('Deal has been added successfully'); // In case result is false throw an error
$.mobile.changePage( "#index", { transition: "slide"} );
}
// This callback function will trigger on successful action
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Error: " . mysql_error() . "Query: " . $query;');
}
});
}
}
// We will use this object to store username and password before we serialize it and send to server. This part can be done in numerous ways but I like this approach because it is simple
var userObject = {
tname : "",
desc : "",
dealid: ""
}
The above should be called when the button is being pressed but most of the time I cant even get to the stage of seeing the button once I add the referecne to this code.
If anybody has had the same issue as this before or can shed some light on the problem I'd really appreciate it.
Your problem is related to jQuery Mobile page handling.
Because you are using multiple HTML pages loaded with ajax into the DOM all your js scripts must be referenced from the first HTML files. All other HTML files will be loaded only partially, only BODY part will be loaded while HEAD is going to be discarded.

Categories

Resources