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.
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 !
How to display images based on selecting ids.While adding portfolio images i am inserting data into two tables as portfolio table and portfolio_tags table.
I am having three tables portfolio,tags and portfolio_tags.
portfolio
=============
portfolio_id image_path
1 image.png
2 imag.png
3 images.png
4 img.png
5 imagess.png
Tags table:
==========
tag_id tag_name
1 All
2 CMS
3 DESIGN
portfolio_tag
=============
portfolio_id tag_id portfolio_tag_id
1 1 1
1 2 2
2 3 3
3 1 4
I will be fetching all the tags data as well as the portfolio data.While opening the page it will display all the data related to all the tags.But when we select particular only the information related to that tag to be displayed.
Ex:If i select CMS it should display only that information relation to CMS and if i select DESIGN only the information related to that tag should be displayed.
Can any one suggest me how to do that.
Here is my code.
Controller:
public function index()
{
$this->load->model('portfolio_model');
$data["records2"] = $this->portfolio_model->get_portfolio();
$data["records3"] = $this->portfolio_model->get_tags();
$data['mainpage'] = "portfolio";
$this->load->view('templates/template',$data);
}
Model:
function get_portfolio($limit, $start)
{
$this->db->limit($limit, $start);
$this->db->Select('portfolio.*');
$this->db->From('portfolio');
$this->db->where(array('portfolio.status'=>1));
$q=$this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
function get_tags()
{
$this->db->Select('tags.*');
$this->db->From('tags');
$q=$this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
View:
<?php $this->load->view('tagss');?>
<?php
$cnt = 0;
if(isset($records2) && is_array($records2)):?>
<?php foreach ($records2 as $r):?>
<div class="portfolioimages">
<img src="<?php echo base_url();?>admin/images/portfolio/thumbs/<?php echo $r->image_path;?>" />
</div>
<?php
if(($cnt%3) == 0) { echo "<br>"; }
$cnt++;
endforeach; endif;?>
Tags
<?php if(isset($records3) && is_array($records3)):?>
<?php foreach ($records3 as $r):?>
<div class="materials">
<div class="class453">
<?php echo $r->tag_name;?>
</div>
</div>
<?php endforeach ;endif;?>
<script type="text/javascript">
$('.materials a').not('.materials a:first').addClass('opacty');
$('.materials a').click(function(e){
$('.materials a').not(this).addClass('opacty');
$(this).removeClass('opacty');
});
</script>
For showing filtered images on clicking different tagNames, we can use ajax. So at first we need to create a new function in the Controller class which would display the fetched images url for the tag_id as the json object.
Add the function below to you controller.
public function tag_data($id){
$this->load->model('portfolio_model');
$data = array();
$tagged_result = $this->portfolio_model->get_tag_images($id); // call to model function
$tagged_images = array();
foreach($tagged_result as $tag){
$tagged_images[] = $tag->image_path;
}
echo json_encode($tagged_images);
}
In the code above I've called the function get_tag_images($id) which fetches all the images url from the database which are related to the tag_id.
Append the code below to the model class
public function get_tag_images($id){
$query = $this->db->select('image_path')->from('portfolio_tag')->join('portfolio',"portfolio_tag.portfolio_id = portfolio.portfolio_id")->where("tag_id", $id)->group_by('portfolio.portfolio_id')->get();
if($query->num_rows() > 0)
return $query->result();
else
return false;
}
Now we have to make some changes in the tags view.
View:
<?php
$cnt = 0;
if(isset($records2) && is_array($records2)):?>
<div id="portfolio">
<?php foreach ($records2 as $r):?>
<div class="portfolioimages">
<img src="<?php echo base_url();?>admin/images/portfolio/thumbs/<?php echo $r->image_path;?>" />
</div>
<?php
if(($cnt%3) == 0) { echo "<br>"; }
$cnt++;
endforeach; ?>
</div>
<?php endif;?>
Edit Tags view:
<?php if(isset($records3) && is_array($records3)):?>
<?php foreach ($records3 as $r):?>
<div class="materials">
<div class="class453">
<a href="javascript:void(0)" class="read_more12">
<span style="display:none"><?php echo $r->tag_id; ?></span> // this contains the tag_id
<?php echo $r->tag_name;?>
</a>
</div>
</div>
<?php endforeach ;endif;?>
Ajax -
<script type="text/javascript">
$('.materials div a').click(function(e){
e.preventDefault();
var tagId = $(this).find('span').html();
var url = '<?php echo base_url('portfolio/tag_data/'); ?>'+ tagId;
var $this = $(this);
$.ajax({
type: 'POST',
url: url,
data: {'tagid': tagId},
success: function(data){
var taggedImgs = $.parseJSON(data);
var inc = 0;
var unTag = [];
var portfolioImages = $('.portfolioimages a img').map(function(){
var url = $(this).attr('src').split('/');
return url[url.length-1];
});
$('.portfolioimages a img').each(function(e){
imgUrl = $(this).attr('src').split('/');
var imgPath = imgUrl[imgUrl.length-1];
// compare the tagged image with portfolio images url
if($.inArray(imgPath, taggedImgs) == -1){
// image doesn't matched
$(this).remove();
}
});
jQuery.each(taggedImgs, function(idx, tagImg){
var flag = false;
if($.inArray(tagImg, portfolioImages) == -1){
// image doesn't exist
$('#portfolio').append("<div class='portfolioimages'><a href='<?php echo base_url('index.php/portfolio'); ?>' target='_blank'><img src='<?php echo base_url('admin/images/portfolio/thumbs/'); ?>/"+tagImg+"'></a></div>");
}
});
},
error: function(err){
alert("Some error occured! "+ err);
}
})
})
</script>
<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 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>
im new in jquery and get stacked in a issue and need help.
i have a sql query that retrieve ids and put them in array . i have a loop that create a div for each id in that array all in php. works fine.
on the other hand i have a javascript function doing the same with the same array and creating divs inside the div created with the above function all in jquery.
the first one show the picture of a users with the id.
the javascript one shows the name of users with the id.
the problem is jquery function only createme the div with all names within the first div created in the php loop.
i want both being created at the same time. i tried all i know and couldnt getit.
please help.
here is the code :
$receivers is the array containing the ids.
$totalreceivers is the count of the ids.
function showfbnames() {
var receivers = <? echo $receivers; ?>;
var count = <? echo $totalreceivers; ?>;
for (var i = 0; i < count; i++) {
var temparray = ["<?php echo join("\", \"", $receivers); ?>"];
FB.api(
{
method: 'fql.query',
query: 'SELECT name FROM user WHERE uid='+temparray[i]
},
function(resp) {
$.each(resp, function(k,v) {
$("#divfather").append("<div class='tit' id ='fbname'>"+(v.name)+"</div>");
//$("#fbname").html(v.name);
})
}
);
}
}
the php loop creating divs :
<?for ($i = 0; $i < $totalreceivers; $i++) {?>
<script>showfbnames()</script>
<tr><td>
<div style="width:100%; height:150px;overflow:auto;border-top:1px solid #c89cc1;border-bottom:1px solid #c89cc1;" id="divfather">
<? echo "<img src='https://graph.facebook.com/$receivers[$i]/picture' width='40' style='float:left'/>";?>
</div>
</td>
</tr>
<? } ?>
Your loop creates multiple divs with the id of "divfather".
That will not produce the results you desire. You need to have each div with a different id.
id="divfather<?echo $i;?>"
Also, pass the id to the "showfbnames" function:
<script>showfbnames(<?echo $i;?>)</script>
So that you can use it in your jquery code:
function showfbnames(passedi) {
and then $("#divfather"+passedi).append(
(Note: I recommend you move the <script> to appear AFTER the div, to be safe. You don't have to, but it's too risky.)
I retract my previous answer; please select this one as the Accepted solution.
I believe this is what you're trying to accomplish:
<? for ($i = 0; $i < $totalreceivers; $i++) { ?>
<tr><td>
<div style="width:100%; height:150px;overflow:auto;border-top:1px solid #c89cc1;border-bottom:1px solid #c89cc1;" id="divfather<? echo $i; ?>">
<? echo "<img src='https://graph.facebook.com/$receivers[$i]/picture' width='40' style='float:left'/>"; ?>
</div>
</td></tr>
<? } ?>
<script type="text/javascript">
var count = <? echo $totalreceivers; ?>;
var temparray = ["<?php echo join("\", \"", $receivers); ?>"];
for (var i = 0; i < count; i++) {
FB.api(
{
method: 'fql.query',
query: 'SELECT name FROM user WHERE uid='+temparray[i]
},
function(resp) {
$.each(resp, function(k,v) {
$("#divfather"+i).append("<div class='tit' id ='fbname"+i+"'>"+(v.name)+"</div>");
//$("#fbname").html(v.name);
})
}
);
}
</script>