I am trying to implement an infinite scroll in my application but at the moment of reaching the end of my page, this throws the error that places.
This is the ajax code:
<script type="text/javascript">
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
var last_id = $(".post-id:last").attr("id");
loadMoreData(last_id);
}
});
function loadMoreData(last_id){
$.ajax(
{
url: '/loadMoreData.php?last_id=' + last_id,
type: "get",
beforeSend: function()
{
$('.ajax-load').show();
}
})
.done(function(data)
{
$('.ajax-load').hide();
$("#post-data").append(data);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('server not responding...');
});
}
</script>
Here, is where I show the data from th DataBase:
<?php while ($post = $result -> fetch(PDO::FETCH_ASSOC)){ ?>
<div class="box-list" id="post-data">
<div class="item">
<div class="row">
<p class="post-id hidde" id="<?php echo $post['id']; ?>">
<div class="col-md-1 hidden-sm hidden-xs">
<div class="img-item"><img src="<?php echo OTRA; ?>/images/<?php echo $post['thumb']; ?>" alt=""></div>
</div>
<div class="col-md-11">
<h3 class="no-margin-top"><?php echo $post['titulo']; ?> <i class="fa fa-link color-white-mute font-1x"></i></h3>
<h5><span class="color-black"><?php echo $post['company']; ?></span> - <span class="color-white-mute"><?php echo $post['locacion']; ?></span></h5>
<p class="text-truncate "><?php echo $post['extracto']; ?></p>
<div>
<span class="color-white-mute"><?php echo fecha($post['fecha']); ?></span>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
and this id the other PHP file to load more data:
<?php session_start();
require 'extras/config.php';
require 'functions.php';
comprobarSession();
$conexion = conexion($bd_config);
$qry = "SELECT * FROM publications WHERE id > '$_GET['last_id']' ORDER BY id DESC LIMIT 8";
$result = $conexion->query($qry);
print_r ($result);
$json = include('views/empleos.php');
echo json_encode($json);
on the Developer Tool of Chrome the error that show me is
jquery.js:8706 GET http://localhost/loadMoreData.php?last_id=9 404 (Not Found)
What is the name of that php file? Sounds like it is not loadMoreData.php? Perhaps it is loadData.php, and the AJAX call should be changed?
Related
This is the script of ajax I am using
mypage.php
$(".sales_anchor").click(function(e)
{
e.preventDefault();
var store_username = $("#storeUsername").val();
var store_id = $("#storeID").val();
var sale_id = $(this).attr('id');
$.ajax(
{
url: 'scripts/sales_sales_products.php',
data: {"store_id": store_id, "sale_id": sale_id,"store_username": store_username},
method: 'POST',
success: function(data)
{
data = $(data).find("div#mainContentOfSale");
$("#contents").html(data);
console.log(data);
}
});
})
<div id="contents"></div>
And
sales_sales_products.php
include_once '../includes/custom_functions.php';
$stmtgetallsales = $mysqli->prepare("SELECT * FROM store_sales ss
INNER JOIN store s ON s.store_id=ss.store_id
WHERE s.store_id=?");
$stmtgetallsales->bind_param("i",$_POST['store_id']);
$stmtgetallsales->execute();
$getallsales = $stmtgetallsales->get_result();
$sales_rows = $getallsales->num_rows;
$stmtgetallsales->close();
?>
<script src="js/3.1.1/jquery.min.js"></script>
<script src="../js/jquery.countdown.min.js"></script>
<div class="container" id="mainContentOfSale">
<?php while($allsales = $getallsales->fetch_assoc())
{
$stmtgetsaleproducts = $mysqli->prepare("SELECT * FROM store_products sp
INNER JOIN store_sale_products ssp ON sp.product_id = ssp.product_id
WHERE ssp.sale_id=? AND sp.store_id=?");
$stmtgetsaleproducts->bind_param("ii",$allsales['sale_id'],$_POST['store_id']);
$stmtgetsaleproducts->execute();
$getsaleproducts = $stmtgetsaleproducts->get_result();
$sale_product_rows = $getsaleproducts->num_rows;
$stmtgetsaleproducts->close();
?>
<script>
$(document).ready(function() {
$('.products_title').hide();
$(".timer").each(function() {
var time = this.id;
var timeLeft = time.split('-').reverse().join('-');
$(this).countdown(timeLeft, function(event) {
$(this).text(event.strftime("%D days %H hours %M minutes %S seconds remaining"));
});
})
});
</script>
<div class="sale_title">
<h2 class="title" id="sale_products"><?php echo $allsales['sale_name']; ?></h2> <span class="badge"><?php echo $sale_product_rows; ?></span> <span class="timer" id="<?php echo $allsales['sale_till']; ?>"></span></div>
<div class="sale_title"><span class="discount">Discount: <span class="color-text"><?php echo $allsales['sale_discount']; ?></span>%</span></div>
<div class="product_area wrapper ">
<?php while($saleproducts = $getsaleproducts->fetch_assoc()){?>
<div class="product">
<a href="<?php echo " index.php?store=".$_POST['store_username']." &view=single&product=".$saleproducts['product_id']; ?>">
<div class="product-image">
<img src="<?php echo image_check($saleproducts['product_image1']); ?>" />
</div>
</a>
<div class="product-details">
<div class="product-name">
<a class="name" href="<?php echo " index.php?store=".$_POST['store_username']." &view=single&product=".$saleproducts['product_id']; ?>"><span><?php echo substr($saleproducts['product_name'], 0, 20); ?></span></a>
</div>
<div class="product-price">
<span class="price"># Rs. <?php echo sale_price($allsales['sale_discount'],$saleproducts['product_price']); ?>/</span>
</div>
</div>
</div>
<?php }?>
<?php } ?>
When I call the anchor tag with class sales_anchor it calls this script and in the inspect element and in network tab when I check the script it does populated the data and html and everything is fine. But it isn't getting called in the current page and in contents div. What am I doing wrong?
You are encountering an JSON.parse error in your screenshot. (Notice the red bar above your result window saying SyntaxError: JSON.parse: unexpected character at line 1 column 9 of the JSON data)
This is because $.ajax is trying to parse the response as a JSON string to an object (the default behaviour).
Please change your ajax function to this:
$(".sales_anchor").click(function(e)
{
e.preventDefault();
var store_username = $("#storeUsername").val();
var store_id = $("#storeID").val();
var sale_id = $(this).attr('id');
$.ajax(
{
url: 'scripts/sales_sales_products.php',
dataType: "text",
data: {"store_id": store_id, "sale_id": sale_id,"store_username": store_username},
method: 'POST',
success: function(data)
{
data = $(data).find("div#mainContentOfSale");
$("#contents").html(data);
console.log(data);
}
});
})
<div id="contents"></div>
I have the below code for User Rating & Comment system which is working fine, but user can post and rate again and again.
I want that if a user posted comment already he/she should not see the comment box but a message that " You have already posted comment on this page".
I tried by using the query in the Add-Comment.php but did not worked.
Need help to solve this issue. Thanks
URL: index.php?id=1
Add-Comment.php
<?php
session_start();
$ipaddress = $_SERVER["REMOTE_ADDR"];
$users = session_id();
if(!empty($_POST)){
extract($_POST);
if($_POST['act'] == 'add-com'):
$comment = htmlentities($comment);
$rating = htmlentities($rating);
// Connect to the database
require_once '../../inc/db.php';
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . "?d=" . $default . "&s=" . $size;
$sql = "INSERT INTO rest_rating (rate, comment, sr_id, ip, user)
VALUES ('$rating', '$comment', '$id_post', '$ipaddress', '$users')";
$sqls = "select user from rest_rating
where sr_id = '$id_post' and user ='$users' )";
$tt = $db->query($sqls);
if ( $tt['user'] == $users ) {
echo '<font size="3" color="red">You Have Already Rated For This Restaurant</font>';
}elseif ( $db->query($sql)==true) {
?>
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" alt="" />
<div class="thecom">
<!--<h5><?php echo $name; ?></h5>-->
<b>Rating : </b><?php echo $rating; ?>
<span class="com-dt"><?php echo date('d-m-Y H:i'); ?></span>
<br/>
<p><?php echo $comment; ?></p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<?php endif; ?>
<?php } ?>
index.php
<?php
require_once '../../inc/db.php';
$id=$_GET['id'];
?>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<link type="text/css" rel="stylesheet" href="css/example.css">
<link href="css/star-rating.css" media="all" rel="stylesheet" type="text/css"/>
<script src="js/star-rating.js" type="text/javascript"></script>
<div class="container">
<h3>Comments</h3>
<?php
$id_post = $id;
?>
<div class="cmt-container" >
<?php
session_start();
$users = session_id();
$results = $db->query("SELECT * FROM rest_rating WHERE sr_id = $id_post");
foreach ($results as $affcom) {
$comment = $affcom['comment'];
$rating = $affcom['rate'];
$date = $affcom['date'];
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . "?d=" . $default . "&s=" . $size;
?>
<div class="cmt-cnt">
<div class="thecom">
<input id="input-5a" class="rating" value="<?php echo $rating; ?>" data-size="xs" data-show-clear="false" data-show-caption="false" data-readonly="true">
<span data-utime="1371248446" class="com-dt"><?php echo $date; ?></span>
<br/>
<p>
<?php echo $comment; ?>
</p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<div class="new-com-bt">
<span>Write a comment ...</span>
</div>
<div class="new-com-cnt">
<input name="starrating" id="starrating" value="1" type="number" class="rating" min=0 max=5 step=1 data-size="xs2" >
<textarea class="the-new-com"></textarea>
<div class="bt-add-com">Post comment</div>
<div class="bt-cancel-com">Cancel</div>
</div>
<div class="clear"></div>
</div><!-- end of comments container "cmt-container" -->
<?php
$sqls = "select user from rest_rating
where sr_id = '$id_post' and user ='$users' )";
$tt=$db->query($sqls);
$userT=$tt['user'];
?>
<script type="text/javascript">
$(function(){
//alert(event.timeStamp);
$('.new-com-bt').click(function(event){
$(this).hide();
$('.new-com-cnt').show();
$('#name-com').focus();
});
/* when start writing the comment activate the "add" button */
$('.the-new-com').bind('input propertychange', function() {
$(".bt-add-com").css({opacity:0.6});
var checklength = $(this).val().length;
if(checklength){ $(".bt-add-com").css({opacity:1}); }
});
/* on clic on the cancel button */
$('.bt-cancel-com').click(function(){
$('.the-new-com').val('');
$('.new-com-cnt').fadeOut('fast', function(){
$('.new-com-bt').fadeIn('fast');
});
});
// on post comment click
$('.bt-add-com').click(function(){
var theCom = $('.the-new-com');
var starrating = $('#starrating');
if( !theCom.val()){
alert('You need to write a comment!');
}else{
$.ajax({
type: "POST",
url: "add-comment.php",
data: 'act=add-com&id_post='+<?php echo $id_post; ?>+'&rating='+starrating.val()+'&comment='+theCom.val(),
success: function(html){
theCom.val('');
starrating.val('');
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
</script>
</div>
You can construct a query to check whether the user has already posted a comment on that particular page or not, and display the rating and comment box accordingly. Here's the code snippet,
// your code
$results = $db->query("SELECT * FROM rest_rating WHERE sr_id = '". $id_post . "' AND user ='". $users . "'");
if($results->num_rows){
// user has already posted a comment
echo '<p>You have already posted comment on this page</p>';
}else{
// user hasn't posted any comment on this page yet
// display rating and comment box
?>
<div class="new-com-bt">
<span>Write a comment ...</span>
</div>
<div class="new-com-cnt">
<input name="starrating" id="starrating" value="1" type="number" class="rating" min=0 max=5 step=1 data-size="xs2" >
<textarea class="the-new-com"></textarea>
<div class="bt-add-com">Post comment</div>
<div class="bt-cancel-com">Cancel</div>
</div>
<div class="clear"></div>
</div><!-- end of comments container "cmt-container" -->
<?php
}
// your code
I have developed a chat system using javascript and php but the problem is that when a new message is received or the messages are more and more and it got a scroll when new message is receive the user have to scroll custom to go to the bottom so I tried to add the javascript to make the scroll be at bottom but the thing is that it is not working and also getting a javascript error though
here is the error what i got
Uncaught TypeError: Cannot read property 'scrollHeight' of undefined
also I have placed an ajax cache false to refresh chat log every 2 seconds so that the new message can be seen not by refreshing the page by directly refreshing via jquery does it effect this?
here is my code
<div class="sidebar-content">
<?php
$get_query = mysqli_query($connection, "SELECT * FROM users WHERE uid != '".$_SESSION['uid']."'");
while($data_user = mysqli_fetch_assoc($get_query)) {
?>
<div class="contact" onclick="get(<?php echo $data_user["uid"]; ?>);">
<?php if(!empty($data_user["profile_picture"])) { ?>
<img src="<?php echo $data_user["profile_picture"]; ?>" class="contact__photo" />
<?php } else { ?>
<img src="uploads/profile_img.jpg" class="contact__photo" />
<?php } ?>
<span class="contact__name"><?php echo $data_user["fullname"]; ?></span>
<span class="chat__id"><?php echo $data_user["uid"]; ?></span>
<span class="contact__status <?php if($data_user["online_status"] == "Online") { echo "online";} ?>"></span>
</div>
<?php } ?>
<div class="search">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/142996/elastic-srch.png" alt="" class="search__img" />
<input type="text" class="search__input" placeholder="Search" />
</div>
</div>
<div class="chat">
<span class="<?php if($status == "Online") { echo 'online_stat';} else {echo "ofline_stat";} ?>"></span>
<span class="chat__back" onclick="reload();"></span>
<span class="chat__status">status</span>
<div class="chat__person">
<span class="chat__online active"></span>
<span class="chat__name" id="chat_name">Huehue Huehue</span>
<span class="contact__id" id="contact__id">Huehue Huehue</span>
</div>
<div id="chat_messages">
</div>
<script>
$.ajaxSetup({cache:false});
var timeout = setInterval(reloadChat, 2000);
function reloadChat () {
var rid = document.getElementById("contact__id").innerHTML;
$('#msgs').load('includes/messages.php?receipt_id='+rid);
}
$('#chat-scroll').animate({
scrollTop: $('#msgs').get(0).scrollHeight}, 2000);
</script>
</div>
change this line
scrollTop: $('#msgs').get(0).scrollHeight}, 2000);
to
scrollTop: $('#msgs').eq(0).scrollHeight}, 2000);
or
scrollTop: $('#msgs')[0].scrollHeight}, 2000);
After ajax load of html content I need to scroll to specific element. The element has attr data-event-id="" But sometimes this variable $('.timelineToolPanel[data-event-id="'+id+'"]').offset().top; returns 0. Whole ajax code is:
function refreshContent(id)
{
var scrollNumber = 0;
$.ajax({
type: 'POST',
url: '<?php echo Yii::app()->createAbsoluteUrl("user/ajaxEventLoad"); ?>',
dataType:'html',
success:function(data){
$("#eventListBlock").empty().append(data);
if(id!=null) {
console.log(id);
scrollNumber = $('.timelineToolPanel[data-event-id="'+id+'"]').offset().top;
console.log(scrollNumber);
$("html, body").animate({
scrollTo: scrollNumber
}, 1000, function() {
// alert("Finished animating");
});
}
},
error: function(data) { // if error occured
alert("Error occured. please try again");
}
});
}
and html:
<div id="eventListBlock">
<?
$this->renderPartial('/windows/timelineWindow', array(
'dataProvider'=>$dataProvider
));
?>
</div>
with rendering this part:
<div class="cd-timeline-block">
<div class="cd-timeline-icon" style="background: <? echo $data->color ?>">
<i class="fa fa-<? echo $data->icon ?>"></i>
</div>
<div class="cd-timeline-content">
<div class="timelineToolPanel" data-event-id="<? echo $data->id ?>">
<i class="fa fa-pencil timelineToolPanelEdit"></i>
<i class="fa fa-trash timelineToolPanelDelete"></i>
</div>
<h2><? echo $data->title ?></h2>
<p><? echo $data->content ?></p>
<span class="cd-date"><? echo date("d. m. Y", strtotime($data->date_event)); ?></span>
</div>
</div>
where #eventListBlock is fixed container.
custom attributes in html have to be defined with "data-*", otherwise it won't work.
http://www.w3schools.com/tags/att_global_data.asp
name your attr in "data-event-id=" and it should do the job, even when i have not proofed the JS code :D
So i am haveing this page where it is displaying articles andunderneet each article it will have a textarea asking allowing the user to insert a comment.I did the AJAX and it works fine.Some of the validation works fine aswell(Meaning that if the textarea is left empty it will not submit the comment and display an error).The way i am doing this validation is with the ID.So i have multi forms with the same ID.For the commets to be submited it works fine but the validtion doesnt work when i go on a second form for exmaple it only works for the first form
AJAX code
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('#comment');
if (comment.val().length > 1)
{
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data
beforeSend: function(){
//Changeing submit button value text and disableing it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
else
{
alert("Hello");
}
});
});
index.php
<?php
require_once("menu.php");
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="comments.js" type="text/javascript" ></script>
<?php
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['Title']?></h1>
</div>
<div class="textcontainer">
<?php echo $row['Content']?>
</div>
<?php
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['TimeStamp']?>
<b>Author :</b> Admin
</div>
<?php
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
#renderinf the comments
echo '<div class="comment-block_' . $postid .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['Content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['userID']) )
{
?>
<form method="POST" class="post-frm" action="index.php" >
<label>New Comment</label>
<textarea id="comment" name="comment" class="comment"></textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
Again the problem being is the first form works fine but the second one and onwaord dont work properly
try this:
var comment = $('.comment',form);
instead of
var comment = $('#comment');
That way you're targeting the textarea belonging to the form you're validating
ps.
remove the id's from the elements or make them unique with php, all element id's should be unique