I would like to load data (images and some texts) on scroll at the bottom of page. I am using Zend 2 framework and jquery.
view
<section>
<?php
$total_groups = ceil($count / 10);
?>
<script type="text/javascript">
$(document).ready(function () {
var track_load = 0; //total loaded record group(s)
var loading = false; //to prevents multipal ajax loads
var total_groups = <?php echo $total_groups; ?>; //total record group(s)
$('#results').load("/autoload_process.php", {'group_no': track_load}, function () {
track_load++;
}); //load first group
$(window).scroll(function () { //detect page scroll
if ($(window).scrollTop() + $(window).height() == $(document).height()) //user scrolled to bottom of the page?
{
if (track_load <= total_groups && loading == false) //there's more data to load
{
loading = true; //prevent further ajax loading
$('.animation_image').show(); //show loading image
//load data from the server using a HTTP POST request
$.post('/autoload_process.php', {'group_no': track_load}, function (data) {
$("#results").append(data); //append received data into the element
//hide loading image
$('.animation_image').hide(); //hide loading image once data is received
track_load++; //loaded group increment
loading = false;
}).fail(function (xhr, ajaxOptions, thrownError) { //any errors?
alert(thrownError); //alert with HTTP error
$('.animation_image').hide(); //hide loading image
loading = false;
});
}
}
});
});
</script>
<ol id="results">
</ol>
<div class="animation_image" style="display:none" align="center">
<img src="/images/loader.gif">
</div>
<!-- IT SHOULD LOOK LIKE THIS
<?php foreach ($works as $work) : ?>
<img src="/images/works/<?php echo $this->escapeHtml($work->imgSrc); ?>" />
<?php endforeach; ?>
-->
</section>
autoload_process.php
<?php
$items_per_group = 10;
if ($_POST) {
//sanitize post value
$group_number = filter_var($_POST["group_no"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//throw HTTP error if group number is not valid
if (!is_numeric($group_number)) {
header('HTTP/1.1 500 Invalid number!');
exit();
}
//get current starting point of records
$position = ($group_number * $items_per_group);
//Limit our results within a specified range.
$results = $mysqli->query("SELECT id,name,alt as message FROM works ORDER BY id ASC LIMIT $position, $items_per_group");
if ($results) {
//output results from database
while ($obj = $results->fetch_object()) {
echo '<li id="item_' . $obj->id . '">' . $obj->id . ' - <strong>' . $obj->name . '</strong></span> — <span class="page_message">' . $obj->message . '</span></li>';
}
}
unset($obj);
$mysqli->close();
}
?>
I do not think invoking autoload_process.php from jquery is the best way how to load files in Zend2. I think I should somehow call my Controller or my table functions, but no luck yet.
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
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.
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.
i am trying to code endless pagination and having a trouble
$(document).ready(function(){
function lastPostFunc()
{
$('div#lastPostsLoader').html('<div class="load"><div class="label"><font color="black"><b>Loading more...</b></font></div></div>');
$.post("cr/sc/scr.php?lastID="+$(".comment:last").attr("id"),
function(data){
if (data != "") {
$(".comment:last").after(data);
}
$('div#lastPostsLoader').empty();
});
};
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
lastPostFunc();
}
});
});
here goes my php
$result = mysql_query('SELECT * FROM xyz ORDER BY sy DESC LIMIT 15');
while($row = mysql_fetch_object($result)) {
$i++;
echo "<div class='comment' id='" . $i. "'>";
}
and other page to grab data
$pg = $_GET['lastID'];
$i=$pg;
$result = mysql_query('SELECT * FROM xyz ORDER BY sy DESC LIMIT '.$pg.',15');
while($row = mysql_fetch_object($result)) {
$i++;
echo "<div class='comment' id='" . $i . "'>";
}
Im getting a problem in getting value of comment:last
i get 15 value of comment:last after 1st time event loads
i get 15 value of comment:last after 2nd time event loads
which is problem im expecting 30
and on 3rd time event occures it gives 30
and same proccess again 30,30,40,40,50,50
instead of 30,40,50,60,70,80
i tried jquery live(), and i used $_GET cause im fetching from URL
Check to see if you are loading the function somewhere else, because the function loads and stops on mine, and the only way I can get it to mimic what you say is if I load the function again on page load, which will create two calls at the same time. Causing 1-15 and 1-15 and the last number off the page. Then on scroll it loads the function as it's supposed to and keeps on loading, just as you tell it too.
Plus, make sure you are checking that get (or even if you use a post) that goes directly into your database. That is asking for an injection.
EDIT: You should probably load full page (and past) first if you have the data. Then load the scroll function, which won't load if the page isn't full. Which is why it stopped for me.
EDIT2: This is the code I was using in case you want to see. I made a mock database, so I didn't have to match a db to test.
<?php
$scroller = 30;
if ( isset($_GET['hold']) && $_GET['hold'] == '1' ) {
$i = isset($_GET['lastID'])?(int)$_GET['lastID']:0;
$j = $i + $scroller;
//sleep(10);
while( $i < $j ) { // mimic a mysql call and spit it out.
++$i;
echo "<div class='comment' id='${i}'>${i}</div>";
}
exit;
}
?>
<html>
<head>
<script src="jquery-1.7.min.js" type="text/javascript"></script>
<script type="text/javascript">
// I was doing something else with this, but stripped out the code
var scroller = <?php echo $scroller;?>;
$(document).ready(function(){
function lastPostFunc()
{
// this assumes there are already comments on the page, so put a dummy comment
var last = $(".comment:last").attr("id");
$('div#lastPostsLoader').html('<div class="load"><div class="label"><font color="black"><b>Loading more...</b></font></div></div>');
$.post("<?php echo $_SERVER['PHP_SELF']; ?>?hold=1&lastID="+last,
function(data){
if ( data != "" ) {
$(".comment:last").after(data);
}
$('div#lastPostsLoader').empty();
});
};
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
lastPostFunc();
}
});
lastPostFunc();
});
</script>
</head>
<body>
<div class="comment_container">
<div class="comment" id="0"></div>
<div id="lastPostsLoader"></div>
</div>
</body>
</html>
jQuery:
$(document).ready(function(){
$(".reload").click(function() {
$("div#update").fadeOut("fast")
.load("home.php div#update").fadeIn("fast")
});
});
PHP:
function statusUpdate() {
$service_query = mysql_query("SELECT * FROM service ORDER BY status");
$service_num = mysql_num_rows($service_query);
for ($x=1;$x<=$service_num;$x++) {
$service_row = mysql_fetch_row($service_query);
$second_query = mysql_query("SELECT * FROM service WHERE sid='$service_row[0]'");
$row = mysql_fetch_row($second_query);
$socket = #fsockopen($row[3], $row[4], $errnum, $errstr, 0.01);
if ($errnum >= 1) { $status = 'offline'; } else { $status = 'online'; }
mysql_query("UPDATE service SET status='$status' WHERE sid='$row[0]'")
or die(mysql_error());
?>
<ul><li style="min-width:190px;"><?php echo $row[1]; ?></li>
<li style="min-width: 190px;" title="DNS: <?php echo $row[2]; ?>">
<?php echo $row[3] . ':' . $row[4]; ?></li>
<li class="<?php echo $status; ?>" style="min-width:80px;"><div id="update">
<?php echo $status; ?></div></li></ul>
<?php
}
}
?>
<?php statusUpdate(); ?>
I have a button which I press (refresh) and that will then refresh the #update id to hopefully fadeOut all the results, and then fade in the new results... issue is it fades them out okay, but when it brings them back, it's just div on div and div and looks really messy - does not do what it's meant to do (would have to upload a picture to give further information).
In the short, what I want to happen is when you hit the update, they will all fade and then fade in with updated values from the php... I made the php/mysql into a function so then I could call it when i hit that refresh button, thinking that would work, but I don't know how to do that...
Thank-you in advance,
Phillip.
Javascript
$(document).ready(function(){
$(".reload").click(function() {
$("div#update").fadeOut("fast");
$.ajax({
url:'home.php',
data:{type:'getStatus'},
type;'post',
success:function(data){
$('div#update').html(data).fadeIn('fast');
}
});
});
});
php page format
<?php
$type= $_POST['type'];
if($type=="getStatus")
{
//get statuses from data base and return only formatted statuses in html
}
else
{
//your page codes here
//like tags <html>,<body> etc, all regular tags
//<script> tags etc
}
?>
.load("home.php div#update").fadeIn("fast")
That's wrong. You need to use,
$('div#update').load('home.php', function(data) {
$('div#update').html(data).fadeIn("fast");
});
Make sure your PHP file works properly by calling it directly and confirming that it returns the results properly.
Reference : http://api.jquery.com/load
Try this
var $data = $('div#update');
$data.fadeOut('slow', function() {
$data.load('home.php div#update', function() {
$data.fadeIn('slow');
});
});
Just for the reference, it will be better to add an additional page in the same directory (eg: phpcode.php) and then put your php code also in there! then try this:
var $data = $('div#update');
$data.fadeOut('slow', function() {
$data.load('phpcode.php div#update', function() {
$data.fadeIn('slow');
});
});