So I have this website laid out and made but now I need to load more results on scroll. This has been asked on here a million times but I was wondering if there was a simple way to fit into my build. Ideally I'd like to do something with the limit but everything I've seen has been about having an entirely seperate page.
Page example-
$sql = "SELECT * FROM `Products` ORDER BY id LIMIT 0,4 ";
echo "<div class=\"full_container\">";
echo "<div class=\"full\">";
if ($result = mysqli_query($con, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class=\"item_frame\">";
echo "<div class=\"item\">";
echo "<h5>".$row["Name"]."</h5>";
echo "</div>"; #Item End#
echo "</div>"; #Item_Frame End#
JS example-
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
///Where I would have the limit fix
}
});
Would this be able to easily be switched to be able to load more on scroll or do I have to go with the second php page to go with ajax?
To get more information you would probably have to do a call via ajax and then render the new images with the javascript once the data is returned. You could treat this in the same way you would for regular pagination, just remember how many results you've got and enter that into your limit so something like
(function () {
var page = 2,
uri = 'moreImages.php';
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
$.get (uri, {page: page}, function (data) {
page ++;
$('#container').append (data);
});
}
});
}) ();
Then in your PHP page you just need to work out the offset based on your pagination rules
$page = (int) #$_GET['page'] ?: 1;
$numItems = 4;
$start = ($page - 1) * $numItems;
$sql = "SELECT * FROM `Products` ORDER BY id LIMIT {$start}, {$numItems}";
Almost forgot:
It might also be worth sending the request a bit before they get to the bottom of the page to speed things up. Make sure to set a flag in your code to mark that you're waiting for the information and only request more when it's clear or you'll constantly be sending requests while scrolling about.
Related
I have this ajax request code
function hehe2(){
var a = $(".film2numb").val();
return $.ajax({
type : "GET",
url : "php/controller1.php?page=semuafilm",
data : "data="+a,
cache: false,
success: function(data){
$('.semuafilm').load('php/film.php');
},
});
}
and it requests this php code, basically it prints out HTML data from SQL
<?php
$indicator = $_SESSION['p'];
if ($indicator == 'filmbaru') {
# code...
$batas = $_SESSION['a'];
if (!$batas) {
$batas = 1;
}
if ($batas>1) {
$batas = $batas * 8;
}
include('connect.php');
$queryfilm = "select * from tb_film order by film_year desc, film_id desc limit $batas ,8";
$exec = $conn->query($queryfilm);
while ( $f = $exec->fetch_assoc()) {
$tn = str_replace(" ","-",$f['film_name']) ;
?>
<div class='col l3 m3 s6 itemovie'><div><img src="images/dum.jpg" class="lazy" data-original='http://www.bolehnonton.com/images/logo/<?php echo $f["film_logo"]; ?>' width="214" height="317"><div><div><div><p><b><?php echo $f['film_name']; ?></b></p><p>IMDB Rating</p><p><?php echo $f['film_genre']; ?></p><p class='center-align linkmov'><a class='dpinblock browntex' href='?page=movie&filmname=<?php echo $tn; ?>'>PLAY MOVIE</a></p><p class='center-align linkmov'><a class='dpinblock' href=''>SEE TRAILER</a></p></div></div></div></div></div>
<?php
}
?>
and here is the controller
<?php
session_start();
$a = $_GET['data'];
$p = $_GET['page'];
$g = $_GET['genre'];
$_SESSION['a'] = $a;
$_SESSION['p'] = $p;
$_SESSION['g'] = $g;
?>
My question is why every time I click button that binded to the hehe2() function (4-5 times, which requested a lot of images) the page get heavier as I click incrementally(laggy, slow to scroll), is there a way to make it lighter, or is there a way to not store image cache on page or clear every time I click the button that binded to hehe2() function?
I am not sure that my advice will be helpful, I will just share my experience.
First of all you should check your binding. Do you bind click trigger only once?
Sometimes function binds multiple times and it can slow down the page.
You can put code below inside function and check the console
console.log("Function called");
If everything is fine from that point and function fires only once - I would recommend you to change flow a little bit. Is it possible to avoid many clicks in a row? If it is not big deal - you can disable button on click, show loader and enable button when AJAX request is completed. This approach will prevent from making multiple requests at once at page will be faster.
I was working on Unlimited scroll for my website using PHP and JavaScript. I almost made it but there was a problem In my code, after scrolling to the bottom of the page my script should load 15 articles every time I scroll to the bottom and after its done It stops loading more posts, but instead it loads all of the articles and then stops the script when all of the posts are loaded.
My JavaScript code:
<script>
// Unlimited Scroll
$(document).ready(function() {
$('.post-load').hide();
var load = 0;
var nbr = "<?php echo mysql_num_rows($sql); ?>";
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
$('.post-load').show();
load++;
if (load * 15 > nbr) {
$('.post-load').hide();
} else {
$.post("extensions/ajax.php", {
load: load
}, function(data) {
$('.lb').append(data);
$('.post-load').hide();
});
}
}
});
});
extensions/ajax.php File for loading the posts through PHP:
<?php
include 'connect.php';
$load = htmlentities(strip_tags($_POST['load'])) * 2;
$sql = mysql_query("SELECT * FROM articles ORDER BY postNum DESC");
$countBlop = mysql_num_rows($sql);
$queryL = mysql_query("SELECT * FROM articles ORDER BY postNum DESC LIMIT 15,".$countBlop."");
while ($posts = mysql_fetch_assoc($queryL)) {
?>
<div class="article">Echo the posts...</div>
<?php } ?>
Looks to me like your LIMIT syntax is backwards
LIMIT 15,".$countBlop.
should be
LIMIT ".$lastIndex.",15
As is now it would be starting at record 15 and then continuing to load until you reach the total count(as defined by $countBlop)
You will also need to have a way for jQuery to pass the last index to the ajax call.
I've read multiple examples on infinite scrolling, but I find it hard to implement it to my code. Here's the code, where data get shown from MySQL database :
<div class="container" align="center" style="margin-top:100px;margin-bottom:100px"><div class="row">
<?php
$result = mysql_query("SELECT * FROM batai WHERE svarbumas=1 ORDER BY id DESC");
while ($row = mysql_fetch_array($result))
{
extract($row);
$link=$row["linkas"];
echo "<div class='col-md-4'>";
$sites_html = file_get_contents($link);
$html = new DOMDocument();
#$html->loadHTML($sites_html);
$meta_og_img = null;
//Get all meta tags and loop through them.
foreach($html->getElementsByTagName('meta') as $meta) {
//If the property attribute of the meta tag is og:image
if($meta->getAttribute('property')=='og:image'){
//Assign the value from content attribute to $meta_og_img
$meta_og_img = $meta->getAttribute('content');
}
}
list($width, $height) = getimagesize($meta_og_img);
$skaicius = abs($width - $height);
if($width > $height) {
echo "<img src=\"$meta_og_img\" style='height:234px;margin-left:-33%' onclick='window.open(\"$link\", \"_blank\");'>";
}
else if($width < $height) {
if($skaicius < 100){
echo "<img src=\"$meta_og_img\" style='width:234px'
onclick='window.open(\"$link\", \"_blank\");'>";
}
else {
echo "<img src=\"$meta_og_img\" style='width:234px;margin-top:-33%'
onclick='window.open(\"$link\", \"_blank\");'>";
}
}
echo "</div>";
}
?>
Stored in the database is a link to, for example, a internet shop page. What the code does is it takes a image for facebook preview from the link stored in the db, which is tagged og:image and then positions it to center. The problem is that page tries to load every image and that takes a ton of time to load the page, thats why I want to somehow make it into a load on scroll page. Btw, Im using Bootstrap's grid system here. I hope you can help me. P.S. If you don't get what I mean because of my bad english, ask me and I'll try to answer it more clearly
I am working on a site that generates notation for a random musical rhythm based on some user-selected parameters. It does this by using an ajax call, which returns a random set of <img> elements that represent different notes. I have a function that is designed to scale the rhythm to fit in the screen, regardless of it's actual size.
The function is triggered after a successful ajax call, which is triggered by a click event on a button.
My problem is that the function does not work as desired when running the first time the page is loaded.
After the function runs for the first time, the height attribute of all of the <img> elements is somehow set to 0.
However, the function works great if I run the it again (by clicking the button). It also works fine after a page refresh.
Also, I do not have this issue in IE11, only Chrome (I haven't tested other browsers yet).
I have tried wrapping the code in both $(window).load() and $(document).ready() event handlers, but this didn't help.
The site in action can be found at http://www.rhythmrandomizer.com
Any help would be greatly appreciated!
Below is the relevant code:
Event handler for the button:
$("#randomize").click(function(){
//get general options from form
var timeSignature = $("#timeSignature").val();
var phraseLength = $("#phraseLength").val();
//get note options from form
var checked = [];
$("#noteOptions :checked").each(function() {
checked.push($(this).val());
});
//alert user and exit function if nothing is selected
if (checked.length < 1) {
alert("Please select at least one note value");
return;
}
//format note option ids into a delimited string
var noteOptions = "";
for (var i=0; i < checked.length; i++) {
noteOptions += checked[i] + "a";
}
//remove the final comma and space
noteOptions = noteOptions.substr(0, noteOptions.length - 1);
//ajax call
$.ajax("randomize.php", {
data : {
timeSignature : timeSignature,
phraseLength : phraseLength,
noteOptions : noteOptions
},
type : "GET",
success : function(response) {
$("#rhythm").html(response);
scaleRhythm();
},
error : function(xhr, status, errorThrown) {
console.log(status + " | " + errorThrown);
}
});
});
The php file that returns the rhythm notation:
<?php
//MySQL connection variables
$hostname = 'localhost';
$user = ini_get('mysqli.default_user');
$pw = ini_get('mysqli.default_pw');
$database = 'rhytxfpd_rhythmrandomizer';
//Connect to database
try {
$db = new PDO('mysql:host=' . $hostname . ';dbname=' . $database,$user,$pw);
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
//Get values from GET
$timeSignature = $_GET['timeSignature'];
$phraseLength = $_GET['phraseLength'];
$noteOptString = $_GET['noteOptions'];
//Split up note options string
$noteOptions = explode('a', $noteOptString);
//Create sql query
$sql = 'SELECT
noteName,
noteValue,
noteGraphic
FROM
notes
WHERE';
//append noteOptions as WHERE clauses
foreach ($noteOptions as $opt) {
$sql = $sql . ' noteGroupID = ' . $opt . ' OR';
}
//remove final " OR"
$sql = substr($sql, 0, strlen($sql) - 3);
//query the database and get all results as an array
/* This will return a table with the name, graphic, and value of
* the notes that the user selected prior to submitting the form
*/
$stmt = $db->query($sql);
$result = $stmt->fetchAll();
//Get the total number of options selected
$numOpts = count($result);
/***************************/
/** BEGIN PRINTING RHYTHM **/
/***************************/
//div to begin the first measure
echo '<div class="measure" id="m1' . $measure . '">';
//Print time signature
echo '<img class="note" src="notes/' . $timeSignature . '.png" title="time signature ' .
$timeSignature . '/4" alt="time signature ' . $timeSignature . '/4"/>';
//Prints as many measures as indicated by the phrase length selection
$measure = 1;
while ($measure <= $phraseLength) {
//begin a new div for other measures.
if ($measure != 1) {
echo '<div class="measure" id="m' . $measure . '">';
}
//Prints random measure according to time signature
$beats = 0;
while ($beats < $timeSignature) {
//Generate a random number
$random = rand(0, $numOpts - 1);
//Get the random note from results
$note = $result[$random];
//Continues if chosen note will not fit in the measure
if ($beats + $note['noteValue'] > $timeSignature) {
continue;
}
//Prints random note
echo '<img class="note" src="notes/' . $note['noteGraphic'] . '.png" title="' .
$note['noteName'] . '" alt="' . $note['noteName'] . '"/>';
//Adds random note's value to total number of beats
$beats += $note['noteValue'];
//$beats++;
}
//If last measure
if ($measure == $phraseLength) {
echo '<img class="note" src="notes/1.png" title="double barline" alt="double barline"/>';
echo '</div>';
} else {
echo '<img class="note" src=notes/b.png title="barline" alt="barline"/>';
echo '</div>';
}
//Increment to next measure
$measure++;
}
The scaleRhythm() function:
function scaleRhythm() {
//Get width of rhythm at full resolution
var rhythmWidth = $("#rhythm").width();
//Get current screen/window width
var screenWidth = window.innerWidth;
//Compute ratio between curren screen and window widths
var ratio = screenWidth / rhythmWidth;
//Multiply img note height by ratio, then by 90% to provide some
//breathing room on either side of the rhythm
var newHeight = (400 * ratio) * .9;
//Set img note height to new height or 300px, whichever is smaller
if (newHeight < 300) {
$(".note").css("height",newHeight);
//code to center rhythm horizontally
$("#rhythm").css("margin-top",(300-newHeight)/2);
} else {
$(".note").css("height",300);
$("#rhythm").css("margin-top",0);
}
}
Add this javascript to your <script></script>:
$(function(){ $("#randomize").click(); });
This will cause your page to run the function that populates your random elements then (at the end of that function) run the scale function.
I tested it by running it on your page in the chrome console and it worked.
If you put a breakpoint in the scaleRhythm function you'll notice on page load it's not being run. You've defined the function but it is not being called on page load. In fact none of the code you want run (ie: the ajax call) gets called until the first click happens. So what you need to do is trigger the click event on the button like JRulle said.
$("#randomize").click();
Okay so here is your issue.
The first time you click the button, var rhythmWidth = $("#rhythm").width(); evaluates to "0" because it is empty.
Which causes these subsequent functions to be "0" as well:
var ratio = screenWidth / rhythmWidth;
var newHeight = (400 * ratio) * .9;
I would edit your function to be like so:
var rhythmWidth = $("#rhythm").width();
if (rhythmWidth == 0) { rhythmWidth = 10; } //assign some reasonable value here
since your function does not support a rhythmWidth of "0"
This question already has answers here:
How to select the nth row in a SQL database table?
(33 answers)
Closed 9 years ago.
I am trying to load content as the user scrolls from my database. I am trying to load 10 items at a time in order. currently I have achieved everything I want to do except I am loading the first 10 items every time. I don't really know how to keep track of what items were loaded last. If I made a variable it would reset anyways everytime the script is called.
What do I need to change in order for it to load the next 10 items instead of the first 10?
php:
<?php
// database connection info
$conn = mysql_connect('localhost','root','') or trigger_error("SQL", E_USER_ERROR);
$db = mysql_select_db('test',$conn) or trigger_error("SQL", E_USER_ERROR);
//offset
$offset=0;
// number of rows to show per page
$rowsperpage = 10;
// get the info from the db
$sql = "SELECT ID, confession, image FROM test LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
echo '<table border="0" width="600px">';
echo "<tr>";
echo "<td><p>" . '<img src="' . $list['image'] . '" hspace="10" border="1" style="float:left;">' . "</p>";
echo "<p>" . "#" . $list['ID'] . ": " . $list['confession'] . "</p></td>";
echo "</tr>";
echo "</table>";
echo "<br>";
//next ten rows
$offset+=10;
}
?>
javascript:
//load content as page scrolls
function yHandler() {
var content = document.getElementById('content');
var contentHeight = content.offsetHeight;
var yOffset = window.pageYOffset;
var y = yOffset + window.innerHeight;
if (y >= contentHeight) {
// Ajax call to get more dynamic data goes here
content.innerHTML += '<div class="newData"></div>';
document.onload = $.post('test5.php', function (data) {
$('.newData').html(data);
});
}
}
window.onscroll = yHandler;
You need to set some counter to this, for example:
<input type="hidden" value ='counter_value'>
And when you send request, you have to send it with counter value, and in php file dependce on counter value select next 10 items from db. After thet using java script increase counter value by ++. And when you will send again request the value will be +1, and in php make logic to select next items
For example, when you reached the bottom of the page, you want to download next items.
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
///here you have to send ajax to php file to get items
var counter= $('#idOfInputwithCouner').attr('value');
$.ajax({
url: 'youPhpFile.php',
data: "counter=" + counter,
type: 'POST',
processData: false,
contentType: false,
success: function (data) {
alert('data'); //here you will get data from php file
$('#idOfInputwithCouner').attr('value',counter +1); //increase input value
}
})
}
});
you may use pagination logic here, send pageNumber with each call and retrieve data accordingly,