<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. :)
Related
UPDATE:
At this moment I have a basic working instagram image display on my website.
What I like to create is a "load next 12 images" button. When I use "max_id=" directly in my url it is working fine.
Can someone point me in the correct direction to make this work?
This is what I have right now:
<style>
section.instagram img {
float:left;
height: 200px;
margin: 10px;
}
</style>
<?php
$otherPage = 'nasa';
$response = file_get_contents("https://www.instagram.com/$otherPage/?__a=1");
if ($response !== false) {
$data = json_decode($response, true);
$userdata = $data['user'];
$mediadata = $data['user']['media']['nodes'];
if ($data !== null) { ?>
<section class="instagram">
<?php
$cnt = count($mediadata) > 12 ? 12 : count($mediadata);
echo $cnt;
for($i = 0; $i < $cnt; $i++){
?>
<img src="<?php echo $mediadata[$i]['thumbnail_src']; ?>" alt="">
<?php
}
?>
</section>
<?php
} // end of response check
} // end of data null
?>
i just finished a code that does that, but im using javascript, here it is!
<!DOCTYPE html>
<html>
<body>
<p id="add-data"></p>
<a id="LoadMore" >Load More</a>
<!--Add jquery-->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<script>
//Add your token
var token = '[your access token]';
//Declare the var to save the nexturl from the API
nexturl = '';
//First call will load at the beginning of the site
$.ajax({
//Modify the count value to set how many photos you want to load
url: 'https://api.instagram.com/v1/users/self/media/recent/?access_token='+ token + '&count=12',
dataType: 'jsonp',
type: 'GET',
data: {access_token: token},
success: function(data){
//Gather The images of the User
for(i =0;i < data.data.length ;i++){
//this variables are just to save the data and simplify you
// can also use the data.data[] info instead
img = data.data[i].images.low_resolution.url;
img_link = data.data[i].link;
likes = data.data[i].likes.count;
comments = data.data[i].comments.count;
interactions = data.data[i].comments.count + data.data[i].likes.count;
//Appends the variables inside the div
$("#add-data").append("<img src='" + img +"' width='150px' height='150px'> <p>Likes: "+likes+"</p><p>Comments: "+comments+"</p><p>Total Interactions: "+interactions+"</p></div><div class='card-action'><a href='" + img_link + "'>Check Photo</a> ");
}
nexturl = data.pagination.next_url;
},
error: function(data){
console.log(data)
}
});
//Load More Photos From Instagram
//If you click on the Load More text / button / etc it will run again the code
//adding the next 12 photos
$('#LoadMore').click(divFunction);
function divFunction(e){
e.preventDefault();
//Each request from instagram can handle only 33 Images (that's how the API works')
$.ajax({
url: nexturl, // we don't need to specify parameters for this request - everything is in URL already
dataType: 'jsonp',
type: 'GET',
success: function(data){
for(x in data.data){
img = data.data[x].images.low_resolution.url;
img_link = data.data[x].link;
likes = data.data[x].likes.count;
comments = data.data[x].comments.count;
interactions = data.data[x].comments.count + data.data[x].likes.count;
//console.log('Image ID: ' + img_id + ' Image Link: ' + img_link + ' Likes: ' + likes);
i ++;
$("#add-data").append("<div class='col s4'><div class='card horizontal'><div class='card-image'><img src='" + img +"' width='150px' height='150px'></div><div class='card-stacked'><div class='card-content'><p >Likes: "+likes+"</p><p>Comments: "+comments+"</p><p>Total Interactions: "+interactions+"</p></div><div class='card-action'><a href='" + img_link + "'>Check Photo</a></div></div></div></div>");
}
nexturl = data.pagination.next_url;
console.log(tot_nexturl)
},
error: function(result2){
console.log(result2);
}
});
}
</script>
</body>
</html>
Hope this helps !
I currently had found bootstrap image gallery from here https://blueimp.github.io/Bootstrap-Image-Gallery/
I had found that they are using ajax json method to display the image from flikr website. But i currently using php to retrieve the image from database. Anyway i can change the ajax json code to retrieve my image from php other than using json method? Thanks
Here are the ajax json code the code retrieving image from flikr :
// Load demo images from flickr:
$.ajax({
url: 'https://api.flickr.com/services/rest/',
data: {
format: 'json',
method: 'flickr.interestingness.getList',
api_key: '7617adae70159d09ba78cfec73c13be3'
},
dataType: 'jsonp',
jsonp: 'jsoncallback'
}).done(function (result) {
var linksContainer = $('#links'),
baseUrl;
// Add the demo images as links with thumbnails to the page:
$.each(result.photos.photo, function (index, photo) {
baseUrl = 'http://farm' + photo.farm + '.static.flickr.com/' +
photo.server + '/' + photo.id + '_' + photo.secret;
$('<a/>')
.append($('<img>').prop('src', baseUrl + '_s.jpg'))
.prop('href', baseUrl + '_b.jpg')
.prop('title', photo.title)
.attr('data-gallery', '')
.appendTo(linksContainer);
});
});
Here are the sample php code i plan to use to retrieve the image from my database:
<?php
include 'dbConnect.php';
global $conn;
if($kiosk=='0'){
$query = "SELECT * FROM M_Photo WHERE photo_kiosk ='$kiosk' AND photo_deleted ='0' ORDER BY photo_name";
}
else{
$query = "SELECT * FROM I_Photo WHERE photo_kiosk ='$kiosk' AND photo_deleted ='0' ORDER BY photo_name";
}
$result = sqlsrv_query($conn,$query);
while( $row = sqlsrv_fetch_array ( $result, SQLSRV_FETCH_ASSOC )){
?>
<li id="image-1" class="thumbnail">
<a style="background-image:url(Upload/<?php echo $row['photo_data']; ?>);background-size: 100px 100px;background-repeat: no-repeat;" title="<?php echo $row['photo_name']; ?>" href="Upload/<?php echo $row['photo_data']; ?>">
<img class="grayscale" src="Upload/<?php echo $row['photo_data']; ?>" alt="<?php echo $row['photo_name']; ?>" style="width:100px; height:100px" ></a>
</li>
<?php
}
sqlsrv_free_stmt($result);
sqlsrv_close($conn);
?>
Anyway to change the ajax code to achieve that?
Try this php code:
<?php
include 'dbConnect.php';
global $conn;
if($kiosk=='0') {
$query="SELECT * FROM M_Photo WHERE photo_kiosk ='$kiosk' AND photo_deleted ='0' ORDER BY photo_name";
} else {
$query="SELECT * FROM I_Photo WHERE photo_kiosk ='$kiosk' AND photo_deleted ='0' ORDER BY photo_name";
}
$result=sqlsrv_query($conn,$query);
while($row=sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC)) {
}
$row=json_encode($row);
echo $row;
sqlsrv_free_stmt($result);
sqlsrv_close($conn);
?>
And javascript:
<script type="text/javascript">
$.ajax({
url:'your php file address',
dataType:'json'
}).done(function(result) {
var linksContainer=$('#links'), baseUrl;
$.each(result, function(index,photo) {
baseUrl='Upload/'+photo.photo_data;
$('<a/>').append($('<img>').prop('src','Upload/'+photo.photo_data)).prop('href','Upload/'+photo.photo_data).prop('title',photo.name).attr('data-gallery','').appendTo(linksContainer);
});
});
</script>
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 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.
I am querying the database to retrieve contents via Jquery Ajax, and by using SetInterval function it queries the database for new contents every 1 min.
My question is How can i keep track of New contents ? For ex: If database has new contents, I want to Add highlight Class to it. How can that be done ?
the Jquery code for Retrieving contents
$(document).ready(hot_listings());
setInterval( "hot_listings();", 10000 );
var ajax_load = "<img class='loading' src='images/indicator.gif' alt='loading...' />";
function hot_listings() {
$.ajax({
url: "hot_listing.php",
cache: false,
success: function(msg) {
$("#hot_properties").html(msg);
}
});
}
Well, i am including the Php too ..
<?php
include("includes/initialize.php");
// hot properties, featured
$per_page = 3;
global $database;
$listings = Listings::hot_listings();
//while ($listing = $database->fetch_array($listings)) {
foreach ($listings as $listing ) {
$listing_id = $listing->listing_id; //initialize listing_id to fetch datas from other table
$photo = Photos::find_by_id($listing_id); //initialize table photo
$comment = Comments::find_by_id($listing_id);
$comment_count = Comments::count_by_id($listing_id);
$photo_count = Photos::count_by_id($listing_id);
//echo $listing['listing_id'];
?>
<li><span class="imageholder">
<img class="listingimageSmall" src="<?php if (!empty($photo->name)) { echo 'uploads/thumbs/'.$photo->name; } else { echo 'images/no-thumb-100.jpg'; } ?>" width="66" height="66" >
</span>
<h3><?php echo ucfirst($listing->title) . ' in ' . ucfirst($listing->city) ; ?></h3>
<p class="description">
<span class="price">Rs <?php echo $listing->price; ?></span>
<span class="media"> <img src="images/icon_img.jpg" alt="Images" width="13" height="12" /> <?php echo $photo_count;?> Images <img src="images/comments.png" alt="Images" width="13" height="12" /> <?php echo $comment_count; ?> comments </span>
</p>
<div class="clear"> </div>
</li>
<?php } // end of foreach
?>
Answer
I recommend that you change your PHP part to emit JSON data about listings.
This can be accomplished through the use of the PHP function json_encode(). You can read more about json_encode() at http://php.net/manual/en/function.json-encode.php.
Then on the client you'll be able to do this:
$.ajax({
url: "hot_listing.php",
cache: false,
success: function(data) {
last_received_listings = data;
build_html_in('#hot_properties', data);
}
});
In an ajax callback you memorize data that you just received and then build HTML markup out of it.
Since you know what listings you already saw, when you get new listings you'll be able to identify new ones.
var new_listings = detect_new_listings(data, last_received_listings);
last_received_listings = data;
build_html_in('#hot_properties');
highlight_listings(new_listings); // set a CSS class on a div or whatever
More details
Possible implementation of detect_new_listings
function detect_new_listings(original, new) {
var result = [];
for(var i = 0; i < original.length; i++) {
var found = false;
// find similar listing in new
for(var j = 0; j < new.length; j++) {
if(original[i].listing_id == new[j].listing_id) {
found = true;
break;
}
}
if(!found) {
result.push(original[i]);
}
}
return result;
}
You could put all listings inside an array in JS and then compare that with the newly fetched list from the PHP file or you could simply check on a date column containing the date for when the row was added and then through PHP; if row is earlier than 1 minute - go ahead and put a class on the HTML element.