I'm using jquery ,ajax and php to implementing infinite scrolling
the image from database
and the code just works one time when i reach the end of a page and show me the message "No More Content" when there is actually content in the database
here is my cod
index.php
<html >
<?php include($_SERVER["DOCUMENT_ROOT"].'/db.php');
$query = "SELECT * FROM photo ORDER by PhotoNo DESC limit 12";
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$actual_row_count =mysql_num_rows($result);
?>
<head>
<title>Infinite Scroll</title>
<script src="jquery-1.7.2.js" type="text/javascript"></script>
<script type="text/javascript">
var page = 1;
$(window).scroll(function () {
$('#more').hide();
$('#no-more').hide();
if($(window).scrollTop() + $(window).height() > $(document).height() - 200) {
$('#more').css("top","400");
$('#more').show();
}
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$('#more').hide();
$('#no-more').hide();
page++;
var data = {
page_num: page
};
var actual_count = "<?php echo $actual_row_count; ?>";
if((page-1)* 12 > actual_count){
$('#no-more').css("top","400");
$('#no-more').show();
}else{
$.ajax({
type: "POST",
url: "data.php",
data:data,
success: function(res) {
$("#result").append(res);
console.log(res);
}
});
}
}
});
</script>
</head>
<body>
<div id='more' >Loading More Content</div>
<div id='no-more' >No More Content</div>
<div id='result'>
<?php
while ($row = mysql_fetch_array($result)) {
$rest_logo=$row['PhotoName'];
$image="../images/rest/".$rest_logo;
echo '<div><img src='.$image.' /></div>';
}
?>
</div>
</body>
</html>
data.php
<?php
$requested_page = $_POST['page_num'];
$set_limit = (($requested_page - 1) * 12) . ",12";
include($_SERVER["DOCUMENT_ROOT"].'/db.php');
$result = mysql_query("SELECT * FROM photo ORDER by PhotoNo DESC limit $set_limit");
$html = '';
while ($row = mysql_fetch_array($result)) {
$rest_logo=$row['PhotoName'];
$image="../images/rest/".$rest_logo;
$html .= '<div><img src='.$image.' /></div>';
}
echo $html;
exit;
?>
I really nead a help
You see to be setting the variables wrong from a quick look:
var actual_count = "<?php echo $actual_row_count; ?>";
You're using mysql_num_rows() to count the return on your first set of results. But that is limited to 12.
You need to do a second mysql query to get all the images without limi, then count them to get the total number of images in the database.
In index.php your query is only returning 12 rows meaning that $actual_row_count is only ever going to be 12. Instead I would set $actual_row_count to the result of the query "SELECT count
(*) FROM photo".
My personal preference for these sort of things is to return a JSON response which only contains the n responses that are loading and have a template html stored in javascript. The way you've written it will return all the photo's on the last query instead of the last 12 that you want.
Related
I am creating a list of links in main.php using "donemler" table in mySQL database and would like to create a page that shows data from "sikkeler" table (which has a foreing key donemID that is used as a relationship between the two tables) as the user clicks it. (data.php is a part of the index.php which is a infinite scroll page)
Here I tried to call $row["donemID"] with GET method using
$k=$_GET['donemID'] in index.php but did not work.
I have also tried to use SESSIONS method where I add "$_SESSION['donemID']=$row$row["donemID"] to main.php
and called it back in index.php as
$k=$_SESSION['donemID']
but it also did not work.
I would like to learn how to create pages and show relevant data in php.
Thanks in advance!
main.php
<?php
require_once "config.php";
$sql = $conn->query("SELECT * FROM donemler ORDER BY donemID");
if ($sql->num_rows > 0) {
// output data of each row
while($row = $sql->fetch_assoc()) {
echo "<tr><td><a href='index.php?devletID=".$row["devletID"]."&donemID=".$row["donemID"]."'>" .$row["donemler"]. "</a></td></tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
index.php
<script type="text/javascript">
var start = 0;
var limit = 20;
var reachedMax = false;
var dnmID = $_GET("donemID");
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height() )
getData();
});
$(document).ready(function () {
getData();
});
function getData() {
if (reachedMax)
return;
$.ajax({
url: 'data.php',
method: 'POST',
dataType: 'text',
data: {
getData: 1,
start: start,
limit: limit,
dnmID: dnmID,
},
success: function(response) {
if (response == "reachedMax")
reachedMax = true;
else {
start += limit;
$(".results").append(response);
}
}
});
}
</script>
data.php
<?php
if (isset($_POST['getData']) ) {
$conn = new mysqli('localhost', 'usrnm', 'pss', 'db');
$dnmID = $conn->real_escape_string($_POST['dnmID']);
$start = $conn->real_escape_string($_POST['start']);
$limit = $conn->real_escape_string($_POST['limit']);
$sql = $conn->query("SELECT * FROM sikkeler WHERE donemID='$dnmID' ORDER BY kayit_no DESC LIMIT $start, $limit");
if ($sql->num_rows > 0) {
$response = "";
while($data = $sql->fetch_array()) {
$response .= '
<tr>
<td>ICD#'.$data['kayit_no'].'</td>
<td>'.$data['donemi'].'</td>
<td><img src="coin_images/'.$data['resim'].'" border="2" width="200px" /></td>
<td>'.$data['darp'].'</td>
<td>'.$data['tarih'].'</td>
<td>'.$data['birim'].'</td>
<td>'.$data['agirlik'].'</td>
<td>'.$data['cap'].'</td>
<td>'.$data['tip'].'</td>
<td>'.$data['reference'].'</td>
</tr>
';
}
exit($response);
} else
exit('reachedMax');
}
?>
You are checking through two different request methods:
$_POST['getData']
$k=$_GET['donemID']
Since you are using the query strings, it is a GET method to check with.
There is no such variable i.e. getData on main.php
<li>
<a id="collection" href="collections.php">
<span class="glyphicon glyphicon-th white"> Collections</span>
</a>
</li>
<script>
$(document).ready(function(){
$("#collection").click(function(){
$.ajax({
type: 'POST',
url: 'pagination.php',
success: function(data) {
$('#cont').show();
}
});
});
});
</script>
pagination.php :
<?php
require_once "database.php";
$db = new Database();
$perPage = 9;
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$startAt = $perPage * ($page - 1);
$queryTotalRow = "SELECT COUNT(*) FROM image";
$rsetTotalRow = $db->query($queryTotalRow);
$fetchTotalRow = mysqli_fetch_array($rsetTotalRow);
$totalPages = ceil($fetchTotalRow["0"] / $perPage);
$links = "";
for ($i = 1; $i <= $totalPages; $i++) {
$links .= ($i != $page ) ? "<li><a href='collections.php?page=$i'>Page $i</span></a></li> "
: "<li><a href='collections.php?page=$i'>Page $page</a></li> ";
}
$paginationQuery = "select name,image,price,description from image LIMIT $startAt, $perPage";
$result = $db->query($paginationQuery);
if($result){
echo '<div class="containerCollection" id="cont" style="display:none" >';
while($row = mysqli_fetch_array ($result)){
echo '<div style="float:left" class="divEntry">';
echo "<div align='center' class='nameEntry'>".$row['name']."</div>";
echo '<div align="center"><img src="'.$row['image'].'" class="imageEntry"/></div>';
echo "<div align='center' class='priceEntry'>".$row['price']."</div>";
echo "<div class='descEntry'>".$row['description']."</div>";
echo '</div>';
}
echo "<div class='text-center' style='clear:both'>";
echo "<ul class='pagination'>";
echo $links;
echo '</ul>';
echo '</div>';
echo '</div>';
}
?>
why is this not working ? i trigger an ajax call from collection button click , then i want to return some echoes wrapped in div which i set to hide, then i want to show it.
edit : fully updated my pagination.php seems like at fault .
edit2 : solver using this solution jQuery showing div and then Disappearing
Your response isn't on the page yet. You've just echoed it in a Ajax call.
In your success function take the returned data put it on the page then try and show it i.e
success: function(data) {
$('body').append(data);
$('body #cont').show();
}
This is assuming the data is being returned correctly, I'd put something in our pagination.php that says return json_encode($row) then you have the data in a JSON format in your success function to build the elements you want.
Check your payload and responses in the browser when running the code make sure it returns data. You can then specify an explicit html type to be returned in your ajax, finally append the html like follow:
Apply html:
<!--html-->
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery-1.11.3.js"></script>
<script language="javascript" type="text/javascript" src="script.js"></script>
</head>
<body>
<h1>Test header</h1>
<h2 id="idTxt"></h2>
</body>
</html>
Apply javascript:
//javascript
$(document).ready(function() {
var data = 'name=getData'; //data parameter passed through to execute specific functions
$.ajax({
type: "POST",
url: "function.php",
data: data,
dataType: 'json',
success: function(data) {
$("#idTxt").append(data["html"]);
console.log(data["html"]);
},
error: function(data) {
//console.log(data);
}
});
});
Apply php:
//php
<?php
if (isset($_POST["name"]))
{
$string = "<h4> Hi there </h4>"; //build up html as string
$obj = new stdClass();
$obj->html = $string;
echo json_encode($obj);
}
?>
Also try to replace your POST with a get maybe, remember you are trying to get html response data from the server. Good luck hope it helps. :)
I have see the example about search box using JQuery and mysql, But the view more function no work. how to improve the program. When i click the view more i can see the next 10 record. Thanks
<script type="text/javascript">
$(document).ready(function()
{
$("#keywords").keyup(function()
{
var kw = $("#keywords").val();
if(kw != '')
{
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw,
success: function(option)
{
$("#results").html(option);
}
});
}
else
{
$("#results").html("");
}
return false;
});
$(".overlay").click(function()
{
$(".overlay").css('display','none');
$("#results").css('display','none');
});
$("#keywords").focus(function()
{
$(".overlay").css('display','block');
$("#results").css('display','block');
});
});
</script>
<div id="inputbox">
<input type="text" id="keywords" name="keywords" value="" placeholder="Type Your Query..."/>
</div>
</div>
<div id="results"></div>
<div class="overlay"></div>
we extract the value of that key and send it to the search.php
<?php
include('db.php');
//file which contains the database details.
?>
<?php
if(isset($_POST['kw']) && $_POST['kw'] != '')
{
$kws = $_POST['kw'];
$kws = mysql_real_escape_string($kws);
$query = "select * from wp_posts where post_name like '%".$kws."%' and (post_type='post' and post_status='publish') limit 10" ;
$res = mysql_query($query);
$count = mysql_num_rows($res);
$i = 0;
if($count > 0)
{
echo "<ul>";
while($row = mysql_fetch_array($res))
{
echo "<a href='$row[guid]'><li>";
echo "<div id='rest'>";
echo $row['post_name'];
echo "<br />";
echo "<div id='auth_dat'>".$row['post_date']."</div>";
echo "</div>";
echo "<div style='clear:both;'></div></li></a>";
$i++;
if($i == 5) break;
}
echo "</ul>";
if($count > 5)
{
echo "<div id='view_more'><a href='#'>View more results</a></div>";
}
}
else
{
echo "<div id='no_result'>No result found !</div>";
}
}
?>
press the view more result will not show more result.
If I'm not mistaken, you want to bring next 10 with ajax ?
This situation behaves as a pagination,
You have to store the current click count in javascript . WÄ°thout clicking more button, the variable of clickCount is 0, when you click more ,then your variable clickCount=1 ,
while sending ajax , send clickCount to the php.
$.ajax
({
type: "POST",
url: "search.php",
data: "kw="+ kw+"&clickCount="+clickCount,
success: function(option)
{
$("#results").html(option);
}
});
You can query with limit&offset (clickCount )*10, itemCountForEachMoreClick = limit 0,10
when click more
limit 10,10
when click one more
limit 20,10. Do not forget to reset clickCount on keyPress !
php Side
$count = isset($_REQUEST["clickCount"])? $_REQUEST["clickCount"]:0;
$limitAndOffset = $count*10.",10";
$query = "select * from wp_posts where post_name like '%".$kws."%'
and (post_type='post' and post_status='publish') limit ".$limitAndOffset ;
I'm using a star ratings system to display rating data from SQL. Each item that can be rated has unique identifyer variable $id and each rating in ratings tabl has unique identifyer $storyidr. I would like this script to display:
the average rating
the number of times the item has been rated.
The values are retirevable but they display on the page together and I can't see how to seperate them. FOr example, for an item that has an average rating of 4 and has been rated 200 times. when user clicks the data returns via AJAX looking like:
For 'response1' 4"200"
For 'response2' 4"200"
I would like to be able to seperate them to look like:
For 'response1' 4
For 'response2' 200
html page
<div id="products" style="">
<div class="rateit" data-storyidr="<?php echo $id; ?>">
</div>
<div class="averagevote">
<div style="display:block;" id="response<?php echo $id; ?>"><?php echo $avgratep; ?></div><br>
<div style="display:block;" id="response2<?php echo $id; ?>">RaTeD <?php echo $rankcount; ?> TiMeS</div>
</div>
</div>
<?php endwhile; mysqli_close($connection); ?>
<script type ="text/javascript">
$('#currentslide .rateit').bind('rated reset', function (e) {
var ri = $(this);
var value = ri.rateit('value');
var storyidr = ri.data('storyidr');
ri.rateit('readonly', true);
$.ajax({
dataType : 'json',
url: 'rate.php',
data: {storyidr: storyidr, value: value},
type: 'POST',
success: function (data) {
$('#response'+storyidr).replaceWith('Avg rating ' + data.avg + '/5');
$('#response2'+storyidr).replaceWith('Rated ' + data.cnt + ' times');
},
error: function (jxhr, msg, err) {
$('#response').append('<li style="color:red">' + msg + '</li>');
}
});
});
</script>
PHP
<?PHP
$storyidr=$_POST['storyidr'];
$mysqli = mysqli_connect($dbhost,$dbusername,$dbpasswd,$database_name) or die ("Couldn't connect to server.");
if (mysqli_connect_errno($mysqli))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO ratings (storyidr, rank, entry_date) VALUES ('$_POST[storyidr]','$_POST[value]',now());";
$sql .= "SELECT AVG(rank) AS avrank, COUNT(rank) AS countrank FROM ratings WHERE storyidr = $storyidr";
if($mysqli->multi_query($sql))
{ $mysqli->next_result();
if ($result = $mysqli->store_result())
{
$data = mysqli_fetch_assoc($result);
$avrank = $data['avrank'];
$countrank = $data['countrank'];
$avrankr = round($avrank,2);
if(is_null($avrank)){$avrank ="null";}
echo json_encode(array('avg' => $avrankr, 'cnt' => $countrank));
}
}
?>
You should only use json_encode() once and only echo the result of that function. Doing it more than once invalidates your json:
else
{
$results = array();
$results['av'] = $avrankr;
$results['cnt'] = $countrank;
echo json_encode($results);
}
Then, in your javascript, you can access data.av and data.cnt directly:
$('#response'+storyidr).replaceWith('Avg rating ' + data.av +'/5');
$('#response2'+storyidr).replaceWith(data.cnt);
You could also set the dataType parameter in your ajax call as mentioned by #barell, but normally jQuery will figure that out correctly already.
Edit: To avoid the undefined errors you are getting you should do something like:
$results = array('status' => 'fail');
...
if () {
...
if ($result)
{
$results['status'] = 'success';
$results['av'] = $avrankr;
$results['cnt'] = $countrank;
}
}
echo json_encode($results);
Now you can check for data.status first in the success callback of your ajax call and take the appropriate action:
success: function (data) {
if (data.status === 'fail') {
// show a warning message somewhere, this is just an example
alert('No results found!');
} else {
$('#response'+storyidr).replaceWith('Avg rating ' + data.av + '/5');
$('#response2'+storyidr).replaceWith('RaTeD ' + data.cnt + ' TiMeS');
}
},
I think the problem is you don't set the correct header. In the php file, before any output, put this:
header('Content-type: text/json');
And also, instead of write two objects, write it as an array:
echo json_encode(array('avg' => $avrankr, 'cnt' => $countrank));
Now it should work
Then, in your Javascript you will access this data like this:
$('#response'+storyidr).replaceWith('Avg rating ' + data.avg +'/5');
$('#response'+storyidr).replaceWith(data.cnt); // Suppose you want the count here
this is actually a part of huge project so i didnt include the css but im willing to post it here if actually necessary.
Ok i have this code
<html>
<head>
<script src="js/jquery.js"></script>
<script type="text/javascript">
var q = "0";
function rr()
{
var q = "1";
var ddxz = document.getElementById('inputbox').value;
if (ddxz === "")
{
alert ('Search box is empty, please fill before you hit the go button.');
}
else
{
$.post('search.php', { name : $('#inputbox').val()}, function(output) {
$('#searchpage').html(output).show();
});
var t=setTimeout("alertMsg()",500);
}
}
function alertMsg()
{
$('#de').hide();
$('#searchpage').show();
}
// searchbox functions ( clear & unclear )
function clickclear(thisfield, defaulttext) {
if (thisfield.value == defaulttext) {
thisfield.value = "";
}
}
function clickrecall(thisfield, defaulttext) {
if (q === "0"){
if (thisfield.value == "") {
thisfield.value = defaulttext;
}}
else
{
}
}
//When you click on a link with class of poplight and the href starts with a #
$('a.poplight[href^=#]').click(function() {
var q = "0";
$.post('tt.php', { name : $(this).attr('id') }, function(output) {
$('#pxpxx').html(output).show();
});
var popID = $(this).attr('rel'); //Get Popup Name
var popURL = $(this).attr('href'); //Get Popup href to define size
//Pull Query & Variables from href URL
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
//Fade in the Popup and add close button
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<img src="images/close_pop.png" class="btn_close" title="Close Window" alt="Close" />');
//Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
var popMargTop = ($('#' + popID).height() + 80) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
//Apply Margin to Popup
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
//Fade in Background
$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer
return false;
});
//Close Popups and Fade Layer
$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove();
}); //fade them both out
return false;
});
});
</script>
</head>
<body>
<input name="searchinput" value="search item here..." type="text" id="inputbox" onclick="clickclear(this, 'search item here...')" onblur="clickrecall(this,'search item here...')"/><button id="submit" onclick="rr()"></button>
<div id="searchpage"></div>
<div id="backgroundPopup"></div>
<div id="popup" class="popup_block">
<div id="pxpxx"></div>
</div>
</body>
</html>
Ok here is the php file(search.php) where the jquery function"function rr()" will pass the data from the input field(#inputbox) once the user click the button(#submit) and then the php file(search.php) will process the data and check if theres a record on the mysql that was match on the data that the jquery has pass and so if there is then the search.php will pass data back to the jquery function and then that jquery function will output the data into the specified div(#searchpage).
<?
if(isset($_POST['name']))
{
$name = mysql_real_escape_string($_POST['name']);
$con=mysql_connect("localhost", "root", "");
if(!$con)
{
die ('could not connect' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE title='$name' OR description='$name' OR type='$name'");
$vv = "";
while($row = mysql_fetch_array($result))
{
$vv .= "<div id='itemdiv2' class='gradient'>";
$vv .= "<div id='imgc'>".'<img src="Images/media/'.$row['name'].'" />'."<br/>";
$vv .= "<a href='#?w=700' id='".$row['id']."' rel='popup' class='poplight'>View full</a>"."</div>";
$vv .= "<div id='pdiva'>"."<p id='ittitle'>".$row['title']."</p>";
$vv .= "<p id='itdes'>".$row['description']."</p>";
$vv .= "<a href='http://".$row['link']."'>".$row['link']."</a>";
$vv .= "</div>"."</div>";
}
echo $vv;
mysql_close($con);
}
else
{
echo "Yay! There's an error occured upon checking your request";
}
?>
and here is the php file(tt.php) where the jquery a.poplight click function will pass the data and then as like the function of the first php file(search.php) it will look for data's match on the mysql and then pass it back to the jquery and then the jquery will output the file to the specified div(#popup) and once it was outputted to the specified div(#popup), then the div(#popup) will show like a popup box (this is absolutely a popup box actually).
<?
//session_start(); start up your PHP session!//
if(isset($_POST['name']))
{
$name = mysql_real_escape_string($_POST['name']);
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE id='$name'");
while($row = mysql_fetch_array($result))
{
$ss = "<table border='0' align='left' cellpadding='3' cellspacing='1'><tr><td>";
$ss .= '<img class="ddx" src="Images/media/'.$row['name'].'" />'."</td>";
$ss .= "<td>"."<table><tr><td style='color:#666; padding-right:15px;'>Name</td><td style='color:#0068AE'>".$row['title']."</td></tr>";
$ss .= "<tr><td style='color:#666; padding-right:15px;'>Description</td> <td>".$row['description']."</td></tr>";
$ss .= "<tr><td style='color:#666; padding-right:15px;'>Link</td><td><a href='".$row['link']."'>".$row['link']."</a></td></tr>";
$ss .= "</td></tr></table>";
}
echo $ss;
mysql_close($con);
}
?>
here is the problem, the popup box(.popup_block) is not showing and so the data from the php file(tt.php) that the jquery has been outputted to that div(.popup_block) (will if ever it was successfully pass from the php file into the jquery and outputted by the jquery).
Some of my codes that rely on this is actually working and that pop up box is actually showing, just this part, its not showing and theres no data from the php file which was the jquery function should output it to that div(.popup_block)
hope someone could help, thanks in advance, anyway im open for any suggestions and recommendation.
JULIVER
First thought, the script is being called before the page is loaded. To solve this, use:
$(document).ready(function()
{
$(window).load(function()
{
//type here your jQuery
});
});
This will cause the script to wait for the whole page to load, including all content and images
if you're using ajax to exchange data into a php file. then check your ajax function if its actually receive the return data from your php file.