I am trying to include a Facebook like button iFrame that has PHP in it:
<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo $row['id']; ?>&send=false&layout=button_count" style="border: medium none; overflow: hidden; width: 115px; height: 21px;" allowtransparency="true" frameborder="0" scrolling="no"></iframe>
when the site loads this, it displays as in a list:
<ul class="recent-list">
<?php
require("inc/connect.php");
$result = mysql_query("SELECT * FROM entries ORDER BY id DESC LIMIT 0, 20", $link);
while($row = mysql_fetch_array($result)){ ?>
<li id="qoute-<?php echo $row['id']; ?>" class="quote-wrap group">
<span>
<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo $row['id']; ?>&send=false&layout=button_count" style="border: medium none; overflow: hidden; width: 115px; height: 21px;" allowtransparency="true" frameborder="0" scrolling="no"></iframe>
</span>
<div class="quote">
<p>
<?php echo htmlentities($row['quote']); ?>
</p>
</div><!-- /.quote -->
</li>
<?php } ?>
</ul>
But when someone click a button that fetches more list-items, the iFrame should be included...
function getQuotes(start, limit) {
//Clear the recent list element
//$(".recent-list").html("");
var recent = $(".recent-list");
$(".recent-list li").animate({opacity: 0.1} , 800).hide(500);
$.ajax({
url: "quotes.php?start=" + start + "&limit=" + limit,
success: function (data) {
data = jQuery.parseJSON(data)
console.log("success");
//Data should now be a javascript array of objects.
for (i = 0; i < data.length; i++) {
var newElem = jQuery("<li></li>").attr('id', data[i].id).addClass('quote-wrap-group');
newElem.append("<div class='quote'><p>" + data[i].quote + "</p></div>");
$(".recent-list").append(newElem);
}
}
});
}
var currentIndex = 0;
$("#more").click(function () {
getQuotes(currentIndex, 20);
currentIndex += 10;
});
When I try to include the iframe in the js above, nothing happens. No error, nothing is returned...
quotes.php:
$start = $_GET['start'];
$limit = $_GET['limit'];
$sql = "SELECT * FROM entries ORDER BY id DESC LIMIT ".$start.", ".$limit;
$result = mysql_query($sql, $link) or die("Error in query: ".mysql_error());
$data = array();
while($row = mysql_fetch_array($result)) {
array_push($data, $row);
}
echo(json_encode($data));
live version. Click "Get more". The quotes appear, but no like button.
http://kdevs.site40.net/#more
you didn't add the iframe tags while building the <li> it the success function
all you did was adding (for each row):
<li id="54" class="quote-wrap-group">
<div class="quote">
<p>fdggfdgdgdgfdg</p>
</div>
</li>
a better approach will be to make the whole list items on server side, and echo it, and then append the html that you received in the success to the existing list
for example:
your php will look like this:
$data = getData();//Get the data from the database here;
foreach($data as $row):
?>
<li id="qoute-<?php echo $row["id"];?>" class="quote-wrap group">
<span>
<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo row["id"];?>&send=false&layout=button_count" style="border: medium none; overflow: hidden; width: 115px; height: 21px;" allowtransparency="true" frameborder="0" scrolling="no"></iframe>
</span>
<div class="quote"><p><?php echo $row["quote"];?></p></div>
</li>
<?php endforeach; ?>
your javascript function will be:
function getQuotes(start, limit){
$.ajax({
url:"quotes.php?start=" + start + "&limit=" + limit,
dataType: "html",
success: function(response){
$("ul.recent-list").append(response);
}
});
}
this of course trying to show the principle, and not necessarily be the exact code you need to write. You need to add the other functionality (like hiding the previous quotes etc...)
Related
I m trying to replicate code found online for Infinite scroll using PHP and JQuery.
But unfortunately, there is a flaw in the code which makes it only to return 7 posts only and stops fetching other posts upon scrolling down leaving a loader gif at the bottom.
Generally, I wouldn't have asked this question, but the code seems
pretty nice (in laymans terms) which I presume will be very helpful
for rookies like me in the community.
Meanwhile will search other resources and try to answer it by myself.
My code Goes as :
Index.php
<div class="post-wall">
<div id="post-list">
<?php
require_once ('db.php');
$sqlQuery = "SELECT * FROM tbl_posts";
$result = mysqli_query($conn, $sqlQuery);
$total_count = mysqli_num_rows($result);
$sqlQuery = "SELECT * FROM tbl_posts ORDER BY id DESC LIMIT 7";
$result = mysqli_query($conn, $sqlQuery);
?>
<input type="hidden" name="total_count" id="total_count"
value="<?php echo $total_count; ?>" />
<?php
while ($row = mysqli_fetch_assoc($result)) {
$content = substr($row['content'], 0, 100);
?>
<div class="post-item" id="<?php echo $row['id']; ?>">
<p class="post-title"><?php echo $row['title']; ?></p>
<p><?php echo $content; ?></p>
</div>
<?php
}
?>
</div>
<div class="ajax-loader text-center">
<img src="LoaderIcon.gif"> Loading more posts...
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
windowOnScroll();
});
function windowOnScroll() {
$(window).on("scroll", function(e){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
if($(".post-item").length < $("#total_count").val()) {
var lastId = $(".post-item:last").attr("id");
getMoreData(lastId);
}
}
});
}
function getMoreData(lastId) {
$(window).off("scroll");
$.ajax({
url: 'getMoreData.php?lastId=' + lastId,
type: "get",
beforeSend: function ()
{
$('.ajax-loader').show();
},
success: function (data) {
setTimeout(function() {
$('.ajax-loader').hide();
$("#post-list").append(data);
windowOnScroll();
}, 1000);
}
});
}
</script>
getMoreData.php
<?php
require_once('db.php');
$lastId = $_GET['lastId'];
$sqlQuery = "SELECT * FROM tbl_posts WHERE id < '" .$lastId . "' ORDER BY id DESC LIMIT 7";
$result = mysqli_query($conn, $sqlQuery);
while ($row = mysqli_fetch_assoc($result))
{
$content = substr($row['content'],0,100);
?>
<div class="post-item" id="<?php echo $row['id']; ?>">
<p class="post-title"> <?php echo $row['title']; ?></p>
<p><?php echo $content; ?></p>
</div>
<?php
}
?>
Any help is greatly appreciated.
I would set this up differently using classes and controllers etc, but as simple scripts, I might set it up something like:
Create a file called getData.php with this content:
<?php
require_once('db.php');
if (! function_exists('getData')) {
/**
* #param int $offset
* #param int $limit
* #return array|null
*/
function getData($offset, $limit, $conn) {
$offset = (int)$offset;
$limit = (int)$limit;
$sqlQuery = "SELECT * FROM tbl_posts ORDER BY id DESC LIMIT $limit OFFSET $offset";
$result = mysqli_query($conn, $sqlQuery);
$rows = [];
while ($row = mysqli_fetch_assoc($result)) {
$rows[]= $row;
}
return $rows;
}
}
Create another file called index.php with this content:
<?php
require_once ('getData.php');
$offset = (int)($_GET['offset'] ?? 0);
$dataOnly = (int)($_GET['dataOnly'] ?? 0);
$limit = 7;
$rows = getData($offset, $limit, $conn);
$offset+= $limit;
$data = [
'rows' => $rows,
'offset' => $offset,
];
$data = json_encode($data);
// if this is an ajax call, stop here and just spit out our json
if ($dataOnly) {
echo $data;
exit;
}
// otherwise, render the page
$sqlQuery = "SELECT * FROM tbl_posts";
$result = mysqli_query($conn, $sqlQuery);
$total_count = mysqli_num_rows($result);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<style type="text/css">
body {
font-family: Arial;
background: #e9ebee;
font-size: 0.9em;
}
.post-wall {
background: #FFF;
border: #e0dfdf 1px solid;
padding: 20px;
border-radius: 5px;
margin: 0 auto;
width: 500px;
}
.post-item {
padding: 10px;
border: #f3f3f3 1px solid;
border-radius: 5px;
margin-bottom: 30px;
}
.post-title {
color: #4faae6;
}
.ajax-loader {
display: block;
text-align: center;
}
.ajax-loader img {
width: 50px;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="post-wall">
<div id="post-list">
<input type="hidden" name="total_count" id="total_count" value="<?= $total_count ?>" />
<input type="hidden" name="offset" id="offset" value="<?= $offset ?>" />
</div>
<div class="ajax-loader text-center">
<img src="LoaderIcon.gif"> Loading more posts...
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
// load the initial rows on page load
let initialData = <?= $data ?? '' ?>;
if (initialData) {
if (initialData.rows) {
addrows(initialData.rows);
$('.ajax-loader').hide();
}
}
windowOnScroll();
});
function windowOnScroll() {
$(window).on("scroll", function(e){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
console.log('test');
if($(".post-item").length < $("#total_count").val()) {
let offset = $('#offset').val();
getMoreData(offset)
}
}
});
}
function getMoreData(offset) {
$('.ajax-loader').show();
$(window).off("scroll");
let pageUrl = window.location.href.split('?')[0];
$.ajax({
url: pageUrl + '?dataOnly=1&offset=' + offset,
type: "get",
success: function (response) {
response = JSON.parse(response);
if (response.rows) {
addrows(response.rows);
if (response.offset) {
$('#offset').val(response.offset);
}
$('.ajax-loader').hide();
}
windowOnScroll();
}
});
}
function addrows(rows) {
let postList = $("#post-list");
$.each(rows, function (i, row) {
let rowHtml = '<div class="post-item" id="'+row.id+'"><p class="post-title">'+row.title+'</p><p>'+row.content+'</p></div>';
postList.append(rowHtml);
});
}
</script>
</body>
</html>
Now, I cant test this locally so there might be an error or two in there, but that should give you the general idea.
One thing im not 100% sure of is that if ($(window).scrollTop() == $(document).height() - $(window).height()){ condition.
XSS warning
You dont show how these "posts" get added to the database, presumably they come from user submissions on some other form. If that is the case, make sure that you understand what XSS vulnerabilities are and how to prevent them
Can anyone give me a working example of a html page loading it's content with json data using masonry plugin?
I have this code but it doesn't load anything :
PHP file :
<?php
$con = mysqli_connect("localhost", "*", "*", "scratch");
mysqli_query($con,"SET NAMES UTF8"); //é preciso meter isto em utf-8 senão não manda nada
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
$result = mysqli_query($con,"SELECT * FROM posts ORDER BY IdPost DESC") or die;
while($row = mysqli_fetch_assoc($result))
{
$output[]=$row;
}
print(json_encode($output, JSON_UNESCAPED_UNICODE));
mysqli_close($con);
?>
So, it gets me this json :
[{"IdPost":"5","Title":"Social Networks Blueprints","PostContent":"Main Social Networks Blueprints","TypePublic":"1","IdCategory":"1","PostDate":"2014-11-16 00:00:00","PostImage":"http://static.ddmcdn.com/gif/storymaker-best-hubble-space-telescope-images-20092-514x268.jpg","IdUser":"2"},{"IdPost":"3","Title":"* New iPhone 5 ","PostContent":"Check out this new piece of pure technology","TypePublic":"1","IdCategory":"1","PostDate":"2014-11-16 00:00:00","PostImage":"http://images.visitcanberra.com.au/images/canberra_hero_image.jpg","IdUser":"3"},{"IdPost":"2","Title":" New Samsung Galaxy S4 *","PostContent":"The specs are awesome. Check this graphic","TypePublic":"1","IdCategory":"1","PostDate":"2014-11-16 00:00:00","PostImage":"http://www.studiotv.com.au/wp-content/uploads/2014/07/Klimas-website-edited.jpg","IdUser":"2"}]
now the HTML part of the FILE that matters:
<div id="main">
<div id="main-inner">
<div id="container" class="js-masonry"data-masonry-options='{ "columnWidth": 2, "itemSelector": ".item" }'>
<div class="gride-sizer"></div>
<!--Open Modal faz o pop-up-->
<div class="item open-modal">
<!-- CCODIGO PARA 1 SECÇÃO DE COMMENTS -->
<a href="#">
<img src="images/A.jpg"><img>
</a>
<div class="pinMeta">
<p class="pinDescription">
Tenda suspensa na arvore! O sonho de qualquer campista (ou qualquer bêbado) como eu! Não perca tempo, reserve já a sua!
</p>
<div class="pinSocialMeta">
<a class="socialItem likes" href="#">
1 like
</a>
</div>
</div>
<div class="pinUserAttribution">
<a class="attributionItem firstAttribution " href="#">
<img class="attributionImg" style="" src="images/profile.jpg"></img>
<span class="attributionTitle">
Publicado por
</span>
<span class="attributionName">
Pihh
</span>
</a>
<a class="attributionItem lastAttribution " href="#">
<img class="attributionImg" style="" src="images/profile.jpg"></img>
<span class="attributionTitle">
em
</span>
<span class="attributionName">Categoria 1</span>
</a>
</div>
</div>
It might miss a div or two because I copy-pasted it but when using the masonry plugin without json ( for fixed values it loads perfectly ).
now the CSS file:
#container .grid-sizer { width:100%;}
#container .item { width:15%; margin: 14px 7px 0px; background-color:#fff; border-radius: 4px 4px 4px 4px; box-shadow: 0px 4px 5px #888888; }
#container .item img { width:100%; height:400%%; border-radius: 4px 4px 0px 0px; }
#container .item img:hover { background:none repeat scroll rgba(255,255,255,0.1) }
#container .item w2 { width:200%; }
/*placed .open-modal at 400px so I can garantee that page remains in same position on when modals opened*/
.open-modal{
position: relative;
top: 400px;
}
So, this is it, I'm having quite a trouble to make this working and I'm totaly blank on this ( probably because I'm new to html and CSS, my expertise is on android - even the asynk tasks of android are really more easy for me and probably I'm having problems in that but if some one could give me a piece of working code I'll be trully greatfull and start to try to understand it .
Best regards,
Pihh
EDIT: I totally forgot the js part !
<script>
var body = $('body');
toggleModal = function () {
body.toggleClass('body-locked');
modal_container.toggleClass('dp-block');
$.ajax({
type: "POST",
url: "http://localhost/website2/posts.php",
data: '{ "pIdPost":' + $(this).attr('data-item') + ' }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var Posts = response;
// var Posts = response.d;
var $boxes;
$.each(Posts, function (index, post) {
$boxes = $('<img src="' + post.PostImage + '" />');
$('#modal-main').html($boxes); //
// $('.modal-userthumb').attr('src', post.Users.UserImage);
// $('.modal-descriptioncreator').text(post.Users.Name + ' ' + post.Users.Surname);
$('.modal-descriptiontimeago').text('• 4 days ago');
$('.modal-descriptioncontent').text(post.PostContent);
});
$('#container').append($boxes);
$('#container').masonry('appended', $boxes, true);
$('#container').masonry();
},
failure: function (msg) {
alert(msg);
}
});
}
</script>
having an issue with the jquery sortable code - it's not so much the jquery but how my list of images is showing. Prior to adding the sortable code it displayed the images in my wrapper in a grid like formation perfectly - now I have added a little style from the jquery it seems to have thrown it but im not sure why...
here is the Jquery style:
<style>
#sortable { list-style-type: none; margin: 0; padding: 0; width: 450px; }
#sortable li {float: left; }
</style>
Here is my list of images that worked perfectly ok before:
<div id="images">
<hr style="margin-top: 10px" />
<ul id="sortable">
<?php
// get folio for user
if(isset($_GET['userid'])) {
$query = 'SELECT * FROM folio WHERE userid=\'' . $_GET['userid'] . '\' ORDER BY ord';
}
else {
$query = 'SELECT * FROM folio WHERE userid=\'' . $_SESSION['userid'] . '\' ORDER BY ord';
}
$result = mysqli_query($connection, $query);
if(!$result) {
// error with MYSQL
die('Failed to retrieve images! - ' . mysqli_error($connection));
}
// list images
$numRows = mysqli_num_rows($result);
if($numRows < 1) {
echo '';
}
else {
$filepath = 'uploads/folio/';
while($imagerow = mysqli_fetch_assoc($result)) {
?>
<li>
<div class="outimgbox"> <a class="fancybox fancybox.ajax" rel="gallery1" style="text-decoration: none;" data-fancybox-type="ajax" href="profile_image_fancybox.php?imgid=<?php echo $imagerow['imgid']; ?>">
<div id="mainwrapper">
<div id="box-3" class="box"> <img class="uploads" src="<?php echo $filepath . $imagerow['filename']; ?>" alt="<?php echo $imagerow['description']; ?>"/> <span class="caption fade-caption">
<h3 ><?php echo $imagerow['title']; ?></h3>
</span> </div>
</div>
</a> </div>
</li>
<!-- class outingbox -->
<?php }} ?>
</ul>
For some odd reason:
<style>
#sortable { list-style-type: none; }
#sortable li {float: left; }
</style>
This resolved the issue....
I am trying make it so that when a tag name in the list is hovered, it should show a box right where it was tagged (like Facebook).
Here is my code:
Viewtag.php
<?php
$sql = "SELECT * FROM image_tag ORDER BY `pic_id`";
$qry = mysql_query($sql);
$rs = mysql_fetch_array($qry);
if ($rs){
do{
echo '<li rel="'.$rs['pic_id'].'"><label>'.$rs['name'].'</label></li>';
}while($rs = mysql_fetch_array($qry));
}
?>
Index.php
.tagview
{
border:solid 3px #fff;
width:100px;
height:100px;
position:absolute;
display:none;
}
$('#taglist li').on('mouseover mouseout',function(event){
pic_id = $(this).attr("rel");
if (event.type == "mouseover"){
$('#view_' + pic_id).show();
}
if (event.type == "mouseout"){
$('#view_' + pic_id).hide();
}
});
viewlist();
function viewlist()
{
$.post('viewtag.php', function(data){
$('#taglist ol').html(data);
});
}
<?php
$query = mysql_query("SELECT * FROM image_tag");
$run = mysql_fetch_array($query);
if($run){
do{
?>
<div class="tagview" style = "top:<?php echo $top; ?>px; left:<?php echo $left; ?>px;" id="view_<?php echo $number; ?>"></div>
<?php
}while($run = mysql_fetch_array($query));
}
?>
<div id="taglist">
<span class="tagtitle">List of Tags</span>
<ol>
</ol>
</div>
It is quite confusing, so I have posted what I have attempted so far.
First of all pic_id is your variable then why u declared like this without var
pic_id = $(this).attr("rel");
made change in this var pic_id = $(this).attr("rel");
http://www.wellbro.com/view_tutorial?t_cat=3&t_i=3
here is the URL for the tutorial on, "JQuery, PHP - photo tagging system"
I am currently working on this tutorial and would like to add a filter button to it.
I am using jquery to make an element clickable:
<p id="marketing">MARKETING</p>
and the jquery for the element:
// Sort content Marketing
$("#pagination p").click(function () {
Display_Load();
//Loading Data
var pageNum = this.id;
$("#content").load("filter_marketing.php?page=" + pageNum, Hide_Load());
});
The problem that I am getting is when clicking on the paragraph tag will go to 'filter_marketing.php?page=' but will not work (i.e. displays nothing) since the 'var pageNum' is not defined.
the php code for pageNum looks like this:
<?php
//Pagination Numbers
for($i=1; $i<=$pages; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
?>
Im just unsure how to make a button 'marketing' and clicking on it goes to the php page and gets the results in mysql db and displays it with the pagination.
if anyone can help on this, that would be great.
P.S. check the entire script of the tutorial to see the entire structure and how it works.
Tutorial
Edit: Here is the code:
Pagination.php:
<?php
include('config.php');
$per_page = 3;
//Calculating no of pages
$sql = "select * from explore where category='marketing'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pages = ceil($count/$per_page)
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery_pagination.js"></script>
<style>
body { margin: 0; padding: 5; font-family:Verdana; font-size:10px }
a
{
text-decoration:none;
color:#B2b2b2;
}
a:hover
{
color:#DF3D82;
text-decoration:underline;
}
#loading {
width: 100%;
position: absolute;
}
#pagination
{
text-align:center;
margin-left:120px;
}
li{
list-style: none;
float: left;
margin-right: 16px;
padding:5px;
border:solid 1px #dddddd;
color:#0063DC;
}
li:hover
{
color:#FF0084;
cursor: pointer;
}
td{
border:solid 1px #dddddd;
padding:5px;
}
</style>
<div id="loading" ></div>
<div id="content" ></div>
<ul id="pagination">
<?php
//Pagination Numbers
for($i=1; $i<=$pages; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
?>
<p id="marketing">MARKETING</p>
</ul>
<br />
<br />
jquery_pagination.js
$(document).ready(function(){
//Display Loading Image
function Display_Load()
{
$("#loading").fadeIn(900,0);
$("#loading").html("<img src='bigLoader.gif' />");
}
//Hide Loading Image
function Hide_Load()
{
$("#loading").fadeOut('slow');
};
//Default Starting Page Results
$("#pagination li:first").css({'color' : '#FF0084'}).css({'border' : 'none'});
Display_Load();
$("#content").load("pagination_data.php?page=1", Hide_Load());
//Pagination Click
$("#pagination li").click(function(){
Display_Load();
//CSS Styles
$("#pagination li")
.css({'border' : 'solid #dddddd 1px'})
.css({'color' : '#0063DC'});
$(this)
.css({'color' : '#FF0084'})
.css({'border' : 'none'});
//Loading Data
var pageNum = this.id;
$("#content").load("pagination_data.php?page=" + pageNum, Hide_Load());
});
// Editing below.
// Sort content Marketing
$("#pagination p").click(function () {
Display_Load();
//Loading Data
var pageNum = this.id;
$("#content").load("filter_marketing.php?page=" + pageNum, Hide_Load());
});
});
filter_marketing.php:
<?php
include('config.php');
$per_page = 3;
if($_GET)
{
$page=$_GET['page'];
}
$start = ($page-1)*$per_page;
$sql = "select * from explore where category='marketing' order by category limit $start,$per_page";
$result = mysql_query($sql);
?>
<table width="800px">
<?php
while($row = mysql_fetch_array($result))
{
$msg_id=$row['id'];
$message=$row['site_description'];
$site_price=$row['site_price'];
?>
<tr>
<td><?php echo $msg_id; ?></td>
<td><?php echo $message; ?></td>
<td><?php echo $site_price; ?></td>
</tr>
<?php
}
?>
</table>
<?php
//Pagination Numbers
for($mktg=1; $mktg<=$pages; $mktg++)
{
echo '<li class="mktg" id="'.$mktg.'">'.$mktg.'</li>';
}
The problem that I am getting is when
clicking on the paragraph tag will go
to 'filter_marketing.php?page=' but
will not work (i.e. displays nothing)
since the 'var pageNum' is not
defined.
When trying the example page I just get correct page numbers, as shown by Firebug's Net panel. The strange thing I see is that results 10-12 are not shown, i.e. page 1 has results 1-9 and page 2 shows results 13-23 (you should really make it 10 or 20 results per page).
Im just unsure how to make a button
'marketing' and clicking on it goes to
the php page and gets the results in
mysql db and displays it with the
pagination.
Where is 'marketing' in your source code? Can you provide an example of this? I just don't understand this question.
EDIT: I still don't understand this. #marketing hasn't been assigned an onclick-event. Moreover, I would use a button in a form like <input type="submit"> and attaching an onclick-event to it in your JavaScript. That function can call your PHP via AJAX or go to a different URL, returning false when successful to prevent the default action (or just let the button submit your form in the regular way).