This question already has answers here:
php include prints 1
(11 answers)
Closed 2 years ago.
I am using PHP and Ajax to get Data. Data get successfully, but after loaded data at the bottom of loaded data showing "1111111". Why?
I try to find solution on different websites, but i can't. please help me. Advanced Thanks.
please see the attached image
Here is my PHP code (load_more.php) :
<?php
include '../../includes/session.php';
$conn = $pdo->open();
$id= $_POST['last_product_id'];
$output = '';
$stmt = $conn->prepare("SELECT *, COUNT(*) AS numrows FROM products WHERE id < :id ORDER BY id DESC");
$stmt->execute(['id'=>$id]);
$row = $stmt->fetch();
$totalRowCount = $row['numrows'];
$showLimit = 6;
try {
$stmt = $conn->prepare("SELECT * FROM products WHERE id < :id ORDER BY id DESC LIMIT $showLimit");
$stmt->execute(['id'=>$id]);
foreach($stmt as $row){
$product_id = $row['id'];
if (!empty($row['old_price'])){
$cart_wish_btn = '
<small> <del class="taka_sign_sm text-secondary">'.number_format($row['old_price'], 0).'
</del> <span class="ml-2 badge border border-success rounded text-success badge-sm">'.number_format($current_price,0).'% OFF</span></small>';
}
$current_price = 100 -(($row['price'] / $row['old_price']) * 100) ;
$image = (!empty($row['photo'])) ? '../../images/products/'.$row['photo'] : '../../images/noimage.jpg';
$output .= ''.include ('../product/item_view_5.php').'';
}
if($totalRowCount > $showLimit){
$output .= '
<div class="show_more_main" id="show_more_main'.$product_id.'">
<div id="'.$product_id.'" class="show_more"></div>
<div class="loding" style="display: none;"><div class="spinner-border spinner-border-sm text-primary"></div></div>
</div>
';
}
}
catch(PDOException $e){
$output .= $e->getMessage();
}
$pdo->close();
echo $output;
?>
Here is my AJax:
$(document).ready(function() {
//$(document).on('click', '.show_more', function() {
$(window).scroll(function(){
var ID = $('.show_more').attr('id');
if(($(window).scrollTop() == $(document).height() - $(window).height()) && (ID != 0)){
$('.show_more').hide();
$('.loding').show();
$.ajax({
type: 'POST',
url: "../product/load_more.php",
data: 'last_product_id=' + ID,
success: function(html) {
$('#show_more_main' + ID).remove();
$('.load_data_table').append(html);
}
})
}
})
});
Here is my HTML:
<div class="row row-cols-2 row-cols-sm-4 row-cols-md-6 px-2 load_data_table"></div>
<div class="show_more_main" id="show_more_main<?php echo $product_id; ?>">
<div id="<?php echo $product_id; ?>" class="show_more"></div>
<div class="loding" style="display: none;"><div class="spinner-border spinner-border-sm text-primary">
</div>
</div>
</div>
include returns 1 which you assign to $output. You probably want to buffer and get the output of the included file:
ob_start();
include('../product/item_view_5.php');
$output .= ob_get_clean();
If you are doing this frequently then build a function with the above code:
function get_template($file) {
ob_start();
include($file);
return ob_get_clean();
}
And use it thusly:
$output .= get_template('../product/item_view_5.php');
Related
I have below code to get more results on page scroll.
It works fine on localhost and on server laptop/desktop.
It does not work on mobile and does not load more results on scroll.
I cannot figure it out why this is happening or what is causing this not to work on mobile.
<?php
$getItemLID = $dba->prepare('SELECT MAX(id) as id FROM items
where status = ? AND ename like ?');
$getItemLID->bind_param('ss', $status,$param);
$getItemLID->execute();
$resultLID = $getItemLID->get_result();
$rowLID = $resultLID->fetch_assoc();
$thelastid = $rowLID['id'];
$status = 1;
$getscategory = $dba->prepare('SELECT * FROM mytable
where status = ?
order by id asc');
$getscategory->bind_param('s', $status);
$getscategory->execute();
$resultGSC = $getscategory->get_result();
while ($rowGSC = $resultGSC->fetch_assoc()) {
$scid = $rowGSC['id'];
$scename = $rowGSC['ename'];
?>
<div class="message_box" data-id="<?php echo $scid; ?>" style="padding-right: 5px;">
<div class="portfolio-item-wrap" style="border-radius: 3%;">
<span class="portfolio-description">
<h3><?php echo $scename; ?></h3>
</span>
</div>
</div>
<?php } ?>
<div id="msg_loaderw" style="display: none;">
<div class="card">
<div class="card-body">
<div class="d-flex align-items-center">
<strong>Loading...</strong>
<div class="spinner-border ml-auto" role="status" aria-hidden="true">
</div>
</div>
</div>
</div>
</div>
<div id="msg_loader">
</div>
<script>
$(document).ready(function () {
$(window).scroll(function () {
var thislastid = "<?php echo $thelastid; ?>";
if($(window).scrollTop() == ($(document).height() - $(window).height())) {
$("#msg_loaderw").show();
var msg_id = $(".message_box:last").data("id");
$.ajax({
type: "POST",
url: "inc/items/search_items_get.php",
data: {msg_id: msg_id},
cache: false,
success: function (data) {
//Insert data after the message_box
$(".message_boxx").append(data);
if (msg_id == thislastid) {
$("#msg_loaderw").hide();
$("#msg_loader").html('<hr><div class="card"><div class="card-body"><div class="align-items-center"><strong><center>That is all what we have for now.</center></strong></div></div></div>');
}
}
});
}
});
});
</script>
Below is : inc/items/search_items_get.php
<?php
include ('../default/db.php');
if (isset($_POST['msg_id']) && isset($_POST['msg_id']) !== NULL) {
$msg_id = $_POST['msg_id'];
$status = 1;
$limit = 12;
$getItem = $dba->prepare('SELECT * FROM mytable
where id > ? AND status = ?
order by id asc');
$getItem->bind_param('ss', $msg_id,$status);
$getItem->execute();
$resultItem = $getItem->get_result();
while ($rowItem = $resultItem->fetch_assoc()) {
$itemID = $rowItem['id'];
$itemName = $rowItem['ename'];
?>
<div class="message_box" data-id="<?php echo $itemID; ?>" style="padding-right: 5px;">
<div class="portfolio-item-wrap" style="border-radius: 3%;">
<span class="portfolio-description">
<h5><?php echo $itemName; ?></h5>
</span>
</div>
</div>
<?php
}
} else {
echo "Message ID is empty";
}
?>*emphasized text*
It seems it's a script issue just try changing the code a bit , hopefully it will work:
<script>
$(document).ready(function () {
$(window).scroll(function () {
var scrollHeight = $(document).height();
var scrollPosition = $(window).height() + $(window).scrollTop();
if ((scrollHeight - scrollPosition) / scrollHeight === 0) {
$("#msg_loaderw").show();
var msg_id = $(".message_box:last").data("id");
$.ajax({
type: "POST",
url: "inc/items/search_items_get.php",
data: {msg_id: msg_id},
cache: false,
success: function (data) {
//Insert data after the message_box
$(".message_boxx").append(data);
if (msg_id == thislastid) {
$("#msg_loaderw").hide();
$("#msg_loader").html('<hr><div class="card"><div class="card-body"><div class="align-items-center"><strong><center>That is all what we have for now.</center></strong></div></div></div>');
}
}
});
}
});
});
</script>
I used this ajax PHP code for lazy load and filter according to category, i want to combine both of them because lazy load works on first load but doesnt work with category buttons.
My AJAX code sends limit and start values to fetch.php and fetch data in the division
A 2nd ajax code sends cat_id to load-prod.php to filter data on button click
index.php
<div class="row">
<div class="col-md-12 p-3 text-center">
<span>Categories  </span>
<div class="btn-group" role="group" aria-label="Basic outlined example">
<button type="button" class="btn btn-outline-dark active showct" value="">All</button>
<?php echo show_cat(); ?>
</div>
</div>
<div class="col-md-12">
<div class="row row-cols-1 row-cols-md-3 g-4" id="showpr">
</div>
</div>
<div class="col-md-12 text-center p-3" id="datamsg"></div>
</div>
//lazy load
<script>
var limit = 9; //The number of records to display per request
var start = 0; //The starting pointer of the data
var action = 'inactive'; //Check if current action is going on or not. If not then inactive otherwise active
function lazyload(limit, start)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{limit:limit, start:start},
cache:false,
success:function(data)
{
$('#showpr').append(data);
if(data == '')
{
$('#datamsg').html("<button type='button' class='btn btn-dark' disabled>No more data</button>");
action = 'active';
}
else
{
$('#datamsg').html("<button type='button' class='btn btn-outline-dark' disabled>Loading More...</button>");
action = 'inactive';
} }});}
if(action == 'inactive')
{
action = 'active';
lazyload(limit, start);
}
$(window).scroll(function(){
if($(window).scrollTop() + $(window).height() > $(document).height() - 100 && action== "inactive")
{
action = 'active';
start = start + limit;
setTimeout(function(){
lazyload(limit, start);
}, 1000);}});
</script>
//show according to category
<script>
$(document).ready(function(){
$('.showct').click(function(){
var cat_id = $(this).val();
$.ajax({
url:"load-prod.php",
method:"POST",
data:{cat_id:cat_id},
success:function(data){
$("#showpr").html(data);
}});
});});
</script>
load-prod.php
<?php
include ('connect.php');
global $con;
if(isset($_POST["cat_id"]))
{
if($_POST["cat_id"]!='')
{
$cf = "select * from products where c_id = '".$_POST['cat_id']."'";
}
else{
$cf = "select * from products";
}
$filter = mysqli_query($con,$cf);
while ($ctf=mysqli_fetch_array($filter)) {
echo "<div class='col-12'><h5 class='card-title'>".$ctf['name']."</h5>";
}
}
?>
fetch.php
<?php
include ('connect.php');
global $con;
if(isset($_POST["limit"], $_POST["start"]))
{
$query = "SELECT * FROM album ORDER BY id ASC LIMIT ".$_POST["start"].", ".$_POST["limit"]."";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result))
{
echo "<div class='col-12'><h5 class='card-title'>".$row['name']."</h5>" ;
}
}?>
I am loading the latest news article to my home page, I would like to load the next one on click of a button. However I get this error on click: home.php:353 Uncaught ReferenceError: nextNews is not defined. The code I have written will load another article but will not hide the previous one. Any suggestions for this are also welcome.
<script>
$( document ).ready(function() {
var newsCount = 1;
function nextNews(item){
newsCount = newsCount + 1;
$("#newsHome2").load("load-news.php", {
newsNewCount: newsCount
});
}
});
</script>
<?php
$query = $handler->query('SELECT * FROM articles LIMIT 1');
$results = $query->fetchAll(PDO::FETCH_ASSOC);
if ($_GET['sort'] == 'dateTime')
{
$sql = " ORDER BY dateTime";}
for ($i=0; $i < count($results); $i++) {
echo '<div class="col-lg-6 col-xs-12 col-sm-12 height-news82" id="newsHome2">';
echo '<h2 class="ashu">Lastest News</h2><br>';
echo '<p class="news-title78">'.$results[$i]['headline'].' <br>'.'</p>';
echo '<img class="news-img33" src="data:image/png;base64,' .base64_encode( $results[$i]['logo'] ).'"/>';
echo '<p class="news-time">'.$results[$i]['dateTime'].'< br>'.'</p>';
echo '<p class="news-body56">'.$results[$i]['text'].'</p>' ;
echo '</p><br><button id="solo-buttons67">Read More</button>';
echo '<i id="arrow20" class="fa fa-chevron-left fa-1x"></ i><i id="arrow21" onclick="nextNews(this)" class="fa fa-chevron-right fa-1x"></i></div>';
}
?>
Your function 'nextNews' is defined in the anonymous function passed to .ready(). So it can't be called in your html.
Alternative:
Use jquery click event
Define the function outside of the anonymous function
Try this workout Its working fine :)
view file view.php
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<div id="newsHome2"></div>
<script type="text/javascript">
var newsCount = 1;
$( document ).ready(function() {
nextNews(newsCount)
});
function nextNews(newsCount){
newsCount = newsCount + 1;
$.post("load-news.php", { newsNewCount: newsCount }, function(data, status){
$("#newsHome2").html(data);
});
}
</script>
php file load-news.php
<?php
if(isset($_POST['newsNewCount'])) { $newsCount=$_POST['newsNewCount']; } else { $newsCount=1; }
echo '<div class="col-lg-6 col-xs-12 col-sm-12 height-news82" id="newsHome2">';
echo '<h2 class="ashu">Lastest News</h2><br>';
echo '<p class="news-title78">headline '.$newsCount.' <br>'.'</p>';
echo '<img class="news-img33" src="data:image/png;base64,"/>';
echo '<p class="news-time">dateTime '.$newsCount.'< br>'.'</p>';
echo '<p class="news-body56">text '.$newsCount.'</p>' ;
echo '</p><br><button id="solo-buttons67">Read More '.$newsCount.'</button>';
echo '<i id="arrow20" class="fa fa-chevron-left fa-1x"></ i><i id="arrow21" onclick="nextNews('.$newsCount.')" class="fa fa-chevron-right fa-1x"> click here for next </i></div>';
?>
In my code below I am trying to create a load more button using AJAX. I have main.php which includes PHP code for calling blogs from database initially, some jQuery code and a load more button. Then I have ajax_more.php which calls more data from database when load more is clicked. Load more buttons are displayed perfectly and when clicked they change to loading and then disappear. Nothing else happens and main.php still shows those two initial blogs which we call first. Please look into code and help where this code has gone wrong.
main.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.show_more', function () {
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type: 'POST',
url: 'ajax_more.php',
data: 'id=' + ID,
success: function (html) {
$('#show_more_main' + ID).remove();
$('.columns').append(html);
}
});
});
});
</script>
<?php
$query = "
SELECT blogs_id, title, body, posted_by, full_name, bio, posted, category
FROM blogs
INNER JOIN categories
ON categories.category_id=blogs.category_id
WHERE category='cat1' OR category='catt2' OR category='cat3' OR category='cat4'
ORDER BY blogs_id desc
LIMIT 2
";
$result = mysqli_query($con,$query);
$rowCount = mysqli_num_rows($result);
if($rowCount > 0){
while ($row = mysqli_fetch_assoc($result)) {
$blogs_id = $row['blogs_id'];
$title = $row['title'];
$body = $row['body'];
$posted_by = $row['posted_by'];
$full_name = $row['full_name'];
$bio = $row['bio'];
$posted = $row['posted'];
echo "
<div class='db'>
<h2>$title</h2>
<p>$body</p>
<p>$bio</p>
</div>
";
?>
<div class="show_more_main" id="show_more_main<?php echo $blogs_id; ?>">
<span id="<?php echo $blogs_id; ?>" class="show_more" title="Load more posts">Show more</span>
<span class="loding" style="display: none;"><span class="loding_txt">Loading…</span></span>
</div>
ajax_more.php
<?php
if(isset($_POST["blogs_id"]) && !empty($_POST["blogs_id"])) {
$query = "
SELECT blogs_id, title, body, posted_by, full_name, bio, posted, category
FROM blogs
INNER JOIN categories ON categories.category_id=blogs.category_id
WHERE category='Entertainment' OR category='Politics' OR category='Sports' OR category='Travel'
AND blogs_id < ".$_POST['blogs_id']."
ORDER BY blogs_id DESC
LIMIT 2
";
$result = mysqli_query($con,$query);
$rowCount = mysqli_num_rows($result);
if($rowCount > 0){
while ($row = mysqli_fetch_assoc($result)) {
$blogs_id = $row['blogs_id'];
$title = $row['title'];
$body = $row['body'];
$posted_by = $row['posted_by'];
$full_name = $row['full_name'];
$bio = $row['bio'];
$posted = $row['posted'];
echo "
<div class='db'>
<h2>$title</h2>
<p>$body</p>
<p>$bio</p>
</div>
";
?>
You should change your query to this
$query = "SELECT blogs_id, title, body, posted_by, full_name, bio, posted, category FROM
blogs INNER JOIN categories ON categories.category_id=blogs.category_id WHERE
(category='Entertainment' OR category='Politics' OR category='Sports' OR category='Travel')
AND blogs_id < " . $_POST['blogs_id'] . " ORDER BY blogs_id DESC LIMIT 2";
All the OR's must be enclosed in the brackets....
You can follow below technique to load more data with just replacing morebox html.
blog.php
<div class="tutorial_list">
<!-- LOAD YOUR PHP BLOG DATA -->
<div class="loading"><img src="fb-load.gif"/></div>
<!-- More Button here $ID values is a last post id value. -->
<div id="show_more<?php echo $ID; ?>" class="morebox">
more
</div>
</div>
<script>
$(document).on('click', '.show_more', function() {
{
var ID = $(this).attr("id");
if (ID) {
$('.morebox').hide();
$('.loding').show();
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastpost=" + ID,
cache: false,
success: function(html) {
$('.loading').hide();
$('.tutorial_list').append(html);
$("#show_more" + ID).remove(); // removing old more button
}
});
} else {
$(".morebox").html('The End'); // no results
}
return false;
});
</script>
ajax_more.php
<!-- LOAD YOUR PHP BLOG DATA WITH lastpost ID and remember to add below code for load more -->
<!-- More Button here $ID values is a last post id value. -->
<div id="show_more<?php echo $ID; ?>" class="morebox">
more
</div>
I have a PHP script to selected records for comments from a database, and then print them onto the page. What I'd like to happen is that if a user is on a page, and another user comments on an item on said page, it automatically appends the new comment to the bottom. The problem I'm having is that I don't know how to differentiate between all of the statuses.
My code for generating the comments on a status is:
<?php
$rt = ("SELECT * FROM (SELECT comment as comment, byuid as byuid, comuid as comuid, likes as likes, dislikes as dislikes, UNIX_TIMESTAMP(timestamp) as timestamp FROM mingle_comments WHERE onuid = '$sid' AND type = 'status' ORDER BY timestamp DESC LIMIT 2) mingle_comments ORDER BY timestamp ASC"); //query
$result = mysql_query($rt) or die (mysql_error());
if(mysql_num_rows($result) >= 2) {
?>
<div id="sa" style="background:#E0E0E0; padding:5px 5px 5px 5px;">
View all comments...
</div>
<?php
}
while($st = mysql_fetch_assoc($result)) {
$comment = nl2br($st['comment']);
$by = $st['byuid'];
$comuid = $st['comuid'];
$time = $st['timestamp'];
$l = $st['likes'];
$d = $st['dislikes'];
$bq = "SELECT * FROM users WHERE uid = '$by' LIMIT 1";
$bqq = mysql_query($bq) or die (mysql_error());
while($bqr = mysql_fetch_assoc($bqq)) {
$dp = $bqr['dp'];
$fbq = $bqr['fname'];
$sbq = $bqr['sname'];
}
?>
<div id="commentbox" class="<?php echo $comuid; ?>" style="padding:5px 5px 5px 5px;">
<div id="cbi" style=" display:inline; position:relative; ">
<img src="<?php if ($dp == null) { echo 'img/unknown_user.jpg'; } else { echo "pf/" . $by . "/" . $dp; } ?>" width="36px" style=" display:inline; position:relative;"/>
</div>
<div id="cbt" style="position:relative; margin-left:32px; margin-top:-35px;">
<?php echo $fbq . " " . $sbq; ?>
<p class="<?php echo $comuid; ?>" style="position:relative; margin-left:5px;"><?php echo $comment; ?></p>
</div>
<div id="clb" style="background:#E0E0E0; padding-left:5px;">
Like<?php echo time_since($time); ?>
</div>
</div>
<?php
}
?>
TL:DR; How can I automatically fetch new comments and append them to the comments generated in the above script without page refresh.
JQUERY
$(document).ready(function(){
var lastcheck='';
setInterval(function() {
$.ajax({
url: 'URL_TO_PHP_SCRIPT',
type: 'POST',
data: {'lastcheck':lastcheck},
success: function(result){
if (result!='nothing_new'){
lastcheck=result.lastcheck /*Update lastcheck*/
var data=result.data;
$.each(data, function(i,val){
//Foreach comment you do what you need, like append, prepend, etc. data[i]."key" to get the value.
});
}
}
});
}, 15000 /* This will check each 15 seconds, you can change it */);
});
PHP SIDE
$lastcheck=$_POST['lastcheck'];
/*
You should add a date field to each new created comment,then filter by "orderby date > $lastcheck" so you get comments since your last check
You get the new comments here
...
...
..
*/
if (!empty($arrayofnewcomments)){
/*The output*/
echo json_encode(array('lastcheck'=>date('Y-m-d H:i:s'),'data'=>$arrayofnewcomments));
}else{/*No new comments*/
echo 'nothing_new';
}
This is some code I came up with, it's a general Idea but it works. It will check each 15 seconds for new comments.