I'm trying to get this infinite scroll to work. I am not good with php, or javascript which isn't helping me.
It'll load the first 20 posts but for whatever reason I keep getting an error stating "No more posts available" when I go to scroll down to load more posts.
Here is:
index.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Home Page</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
<link href="css/main.css" rel="stylesheet" type="text/css" media="all">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container-fluid no-gutter">
<nav class="navbar navbar-dark bg-dark">
<div class="container">
<h1 class="navbar-brand">Posts</h1>
</div>
</nav>
<div class="container padding">
<div class="row">
<div class="col-3">
</div>
<div class="main col-9" id="post-list">
<input type="hidden" name="total_count" id="total_count" value="<?php echo $total; ?>" />
<?php
include ("config/config.php");
try {
$conn = new PDO("mysql:host=$dbh;dbname=$dbn", $dbu, $dbp);
$sql = "SELECT address, FROM_UNIXTIME(date/1000,'%M %D, %Y %h:%i:%s') as date, body FROM table_name";
$total = $conn->query($sql)->rowCount();
$sql = "SELECT row, address, FROM_UNIXTIME(date/1000, '%M %D, %Y %h:%i %p')as date, body FROM table_name LIMIT 20";
foreach($conn->query($sql) as $row) {
echo '<div class= "home">';
echo '<div class= "address">' . $row["address"] . '</div>';
echo '<div class= "body">' . $row["body"] . '</div>';
echo '<div class= "date">' . $row["date"] . '</div>';
echo '</div>';
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
windowOnScroll();
$("div.address:contains(Var)").parent().removeClass("home");
$("div.address:contains(Var)").parent().addClass("away");
});
function windowOnScroll() {
$(window).on("scroll", function(e){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
console.log('Scrolling')
if($(".home").length < $("#total_count").val()) {
var lastId = $(".home:last").attr("id");
getMoreData(lastId);
}
else{
console.log('No More posts aviliable')
}
}
});
}
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();
}, 10);
}
});
}
</script>
</body>
</html>
getMoreData.php
<?php
include ("config/config.php");
$conn = new PDO("mysql:host=$dbh;dbname=$dbn", $dbu, $dbp);
$lastId = $_GET['lastId'];
$sql = "SELECT row, address, FROM_UNIXTIME(date/1000, '%M %D, %Y %h:%i %p')as date, body FROM table_name WHERE `row` < '" .$lastId . "' LIMIT 20";
foreach($conn->query($sql) as $row) {
echo '<div class="home">';
echo '<div class= "address">' . $row["address"] . '</div>';
echo '<div class= "body">' . $row["body"] . '</div>';
echo '<div class= "date">' . $row["date"] . '</div>';
echo '</div>';
}
?>
I've spent a couple days trying to get this to work with various results.
Please help! lol...
Try placing <input type="hidden" id="total_count" value="<?php echo $total?>"> after the PHP code. Because $total is not initialized yet.
Related
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'm struggling to find a way of displaying the results found on a page of my pagination, for example if a search has only 9 results I get "Showing 10 of 9" and I'd like it to show as "1-10 of 300, 11-20 of 300, or 1-9 of 9 etc".
Here's the code.
<?php
$con = mysqli_connect("localhost", "root", "root", "courses");
// $total = mysqli_query($con, "SELECT count(title) as total")->fetch()['total']);
if(isset($_GET['searchword'])){
$searchword = $_GET['searchword'];
}
else {
$searchword = "";
}
$result = mysqli_query($con, "SELECT count(title) FROM course WHERE concat(award,' ',title) LIKE '%$searchword%'");
$row = mysqli_fetch_row($result);
// Total rows.
$rowstotal = $row[0];
//pages
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = isset($_GET['per-page']) && $_GET['per-page'] <= 100 ? (int)$_GET['per-page'] : 10;
$start = ($page > 1) ? ($page * $perPage) - $perPage : 0;
$pages = ceil($rowstotal / $perPage);
$sql = "SELECT * FROM course WHERE concat(award,' ',title) LIKE '%$searchword%' ORDER BY title ASC LIMIT {$start},{$perPage}";
$query = mysqli_query($con, $sql);
$resultsText = "$rowstotal results";
$resultsList = '';
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$courseId = $row["id"];
$courseAward = $row["award"];
$courseName = $row["title"];
$courseDetails = $row["summary"];
$resultsList .= ''.$courseAward.' '.$courseName.' <br>'.$courseDetails.'<br/>';
}
mysqli_close($con);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Courses</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<nav class="navbar navbar-default navbar-static-top navbar-inverse">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">
<img alt="Napier" src="">
</a>
</div>
</div>
</nav>
<div class="container">
<!-- Search -->
<form method="GET">
<input type="text" class="form-control" id="searchword" name="searchword" placeholder="Search" value="<?php echo $searchword ?>" style="width:30%;"><br>
</form>
<!-- Results -->
<div class="results">
<p></p>
<p>Showing <?php echo $perPage; ?> of <?php echo $resultsText; ?></p>
<p id="content"><?php echo $resultsList; ?></p>
</div>
<div class="pagination">
<?php for($x = 1; $x <= $pages; $x++): ?>
<a href="?page=<?php echo $x; ?>&per-page=<?php echo $perPage; ?>&searchword=<?php echo $searchword; ?>"<?php if($page === $x) { echo ' class="selected"'; } ?>><?php echo $x; ?></a>
<?php endfor; ?>
</div>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#searchword').autocomplete({
source: function(request, response){
$.ajax({
url:"auto.php",
dataType:"json",
data:{term:request.term},
success: function(data){
response(data.slice(0,10));
}
});
},
minLength: 1,
select: function(event,ui){
}
});
});
</script>
</body>
</html>
Update your query :
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM course WHERE concat(award,' ',title) LIKE '%$searchword%' ORDER BY title ASC LIMIT {$start},{$perPage}";
And this query just below the above query. Select found_rows() as tot
This tot will returns the total no of rows (will not consider the limit clause)
I am making use of ajax call to insert data in starting of my page. this is more like a wall post script. Whenever user posts something, the latest post is shown in the top of the posts page.
I am using JS, PHP and an HTML page.
here is my js code:
$(function() {
$("#tweet_submit").click(function()
{
var tweet = $("#tweet").val();
var x = $('.preview').attr('id');
if(x)
var z= x;
else
var z=0;
var dataString = 'tweet='+ tweet+ '&z=' +z;
if(tweet=='')
{
alert('Please type your tweet here');
}
else
{
alert('into post');
$.ajax({
type: "POST",
url: "WallPost/post_tweet1.php",
data: dataString,
cache: false,
success: function(html){
$("#tweet").val('');
$("#preview").hide();
$("#content").prepend(html);
}
});
}return false;
});
});
This is my PHP page:
post_tweet.php
<?php
include("includes/db.php");
include("session.php");
include_once 'includes/time_stamp.php';
//echo "request sent to post";
if($_POST)
{
$tweet=$_POST['tweet'];
$upload_id=$_POST['z'];
$time=time();
$query = "INSERT INTO tweets(tweet,time,upload_id,uid_fk) VALUES ('$tweet','$time','$upload_id','$uid')";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
else
{
$msg ="<br> 1 record added";
}
echo "<br>".$msg;
$sql=mysqli_query($con,"select T.tid, T.tweet, T.time, T.upload_id, U.username, U.fullname, U.email FROM tweets T, users U WHERE T.uid_fk=U.uid and T.uid_fk='$uid' order by T.tid DESC LIMIT 1");
//$show_result=mysqli_query($sql);
while($row=mysqli_fetch_row($sql))
{
echo "data start here";
$tid= "$row[0]";
$tweet= "$row[1]";
$time = "$row[2]";
$img_id= "$row[3]";
$username="$row[4]";
$fullname = "$row[5]";
$email = "$row[6]";
$lowercase = strtolower($email);
$imagecode = md5( $lowercase );
$image_sql=mysqli_query($con,"select image_name from uploads where upload_id='$img_id'");
while($data=mysqli_fetch_row($image_sql))
{
$image_name="$data[0]";
$chars = 7;
$text = $image_name." ";
$text = substr($text,0,$chars);
$imgtext = "pic.twitter/".$text."...";
}
//echo "<div class='center'>";
echo "<div class='tweet_box' id='$tid'>";
echo "<div class='tweet_user'><img class='user_img' src='http://www.gravatar.com/avatar/$imagecode?s=50'></div>";
echo "<div class='tweet_body'>";
?>
<div class='tweet_time'><?php time_stamp($time);?></div>
<?php
echo "<div><b><a href='http://twitter.com/$username'>$fullname</a></b> <span class='uname'>#$username</span></div>";
echo "<div class='tweet_text'>$tweet ";
if($img_id!=0)
{
echo "<a href=''/>$imgtext</a></div>";
}
else
{
echo "</div>";
}
echo "<div class='tweet_options'><div class='first_option'><a href='#'>Expand</a> </div><div class='sub_options'> <a href='#'>Reply</a> <a href='#'>Retweet</a> <a href='#'>Favourite</a></div></div>";
if($img_id!=0)
{
?>
<div class="tweet_image" id="tweetimage<?php echo $tid; ?>">
<center><img src="uploads/<?php echo $image_name; ?>" class="image_show"/></center></div>
<?php
}
echo "</div></div>";
?>
<div class="tweet_reply_box" id="replybox<?php echo $tid;?>">
<div><textarea rel="<?php echo $tid;?>" id="replytext<?php echo $tid;?>" class="reply" name="reply"
maxlength="140">#<?php echo $username;?> </textarea></div>
<div class="reply_button_bar" id="replybutton<?php echo $tid;?>">
<div><input type="submit" value=" Reply " class="reply_btn" id="<?php echo $tid;?>"/></div>
</div>
</div>
<div id="reply_load<?php echo $tid;?>" class="reply_load">
</div>
<?php
}
}
else { }
?>
And this is my HTML page:
Wallpost.php
<!doctype html>
<html>
<head>
<title>Design Modo - Code-pal | eCommerce Website Template - Dead Stocker</title>
<link rel="shortcut icon" href="http://www.code-pal.com/wp-content/themes/codpeal-new/favicon.ico">
<link rel="stylesheet" type="text/css" href="css/check_style.css" />
<link rel="stylesheet" href="css/wallpost/wtfdiary.css">
<link rel="stylesheet" href="css/wallpost/tipsy_title.css">
<script type="text/javascript" src="WallPost/js/jquery.min.js"></script>
<script type="text/javascript" src="WallPost/js/jquery.tipsy.js"></script>
<script src="WallPost/js/twitter.js"></script>
<script type="text/javascript" src="WallPost/js/jquery.form.js"></script>
</head>
<body>
<div class="page-wrap">
<div class="clear"></div>
<?php include("header.php"); ?>
<div class="clear"></div>
<div class="body-contents">
<?php include("left-body1.php"); ?>
<div class="center">
<br>
<div class="txthead"><strong>Share thoughts here</strong></div>
<?php
include("WallPost/index.php");
?>
</div>
</div>
<?php include("right-body.php"); ?>
<div class="clear"></div>
</div>
<!-- eo .body-content -->
<?php include("footer.php"); ?>
</div><!-- eo .page-wrap-->
Here is the code where i post tweet:
index.php under WallPost folder:
<?php
include("includes/db.php");
include("session.php");
include("includes/time_stamp.php");
?>
<html>
<head>
<link rel="stylesheet" href="css/wtfdiary.css">
<link rel="stylesheet" href="css/tipsy_title.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.tipsy.js"></script>
<script type="text/javascript" src="js/twitter.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
</head>
<body>
<div id="container">
<div id="sidebar_container">
<div id="sidebar">
<div id='logo'><img src='images/1.png'></div>
<div id="box">
<div><textarea id="tweet" name="tweet" placeholder="Compose new Tweet..."></textarea></div>
<div id='preview'></div>
<div id="button_bar">
<div id="icons">
<div class="filebutton" title="Image Upload">
<form id="imageform" method="post" enctype="multipart/form-data" action='ajax_image.php'>
<span><input type="file" name="photoimg" id="photoimg"/></span>
</form>
</div>
</div>
<div><input type="submit" value=" Tweet " class="btn" id="tweet_submit"/></div>
</div>
</div>
</div>
</div>
<!-- <div id="main"> -->
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id='heading'>Tweets</div>
<div id='content'>
<?php include("loads_tweets1.php");?>
<!-- </div> -->
</div>
</div>
</body>
</html>
So after i make use of all these code, Post is shown in my page, but the way it is shown is not correct.
The post is inserted at some random place. (I couldn't attach image due to less reputation)
Can someone please tell what is going wrong, and i am not able to get this data in correct place where my other posts are listed.
Thanks in advance!!!
Your input helped me and i was able to solve it. Content was being called at two places, and ajax inserted the data on first location and i was not getting it placed where i needed it.
Thanks.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Little Things</title>
<?php echo link_tag('resources/css/style.css'); ?>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript" src="<?php echo base_url('resources/js/script.js');?>" ></script>
<script type="text/javascript">var $rows = $('#table tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
</script>
</head>
<body>
<div id="container">
<div id="top">
<img id="logo" src="<?php echo base_url('resources/images/logo.jpg'); ?>" alt="litLogo"/>
</div>
<div id="main">
<div id='cssmenu'>
<ul>
<li class='active'><span>Home</span></li>
<li class="element"><a href='#'><span>Shopping Cart</span></a></li>
<li class="element"><a href='#'><span>Wish List</span></a></li>
<li class="element"><a href='#'><span>Contact</span></a></li>
<li id="name">
<?php
if($this->session->userdata('email'))
{
echo "<a href='#'><span>Welcome ".$user."!</span></a>";
}
else
{
echo "<a href='#'><span>Welcome Guest!</span></a>";
}
?>
<?php
if($this->session->userdata('email'))
{
echo '<li class="element"><span>Logout</span></li>';
}
else
{
echo '<li class="element"><span>Login</span></li>';
}
?>
</li>
<li class="element"><span>Sign Up</span></li>
</ul>
</div>
<div class="tables" id="tables">
<input type="text" class="search" placeholder="Type to search">
<?php
$imgDir="../../resources/images/thumbs/";
echo "<table id='table'>";
echo "<tbody class='list'>";
echo "<tr bgcolor='#E60000'>";
echo "<th>Name</th><th>Product Line</th><th>Product Scale</th><th>Product Description</th><th>Price</th><th>Image</th>";
echo "</tr>";
$i=0;
foreach($Products as $key => $value)
{
$i++;
if($i%2==0)
{
echo "<tr bgcolor='#EE4D4D' width='100%'>";
//echo '<td>'.$value["ID"].'</td>';
echo "<td class='pName'>".$value["productName"]."</td>";
echo "<td class='pLine'>".$value["productLine"]."</td>";
echo "<td class='pScale'>".$value["productScale"]."</td>";
echo "<td class='pDes'>".$value["productDescription"]."</td>";
echo "<td class='buyPrice'>".$value["buyPrice"]."</td>";
//echo '<td>'.$value["QtySold"].'</td>';
echo "<td class='image'><img src='".$imgDir.$value['image']."' height='100' width='100'/></td>";
//echo '<td>'.$value["ABV"].'</td>';
echo "</tr>";
}
else
{
echo "<tr bgcolor='#F28080' width='100%'>";
//echo '<td>'.$value["ID"].'</td>';
echo "<td class='pName'>".$value["productName"]."</td>";
echo "<td class='pLine'>".$value["productLine"]."</td>";
echo "<td class='pScale'>".$value["productScale"]."</td>";
echo "<td class='pDes'>".$value["productDescription"]."</td>";
echo "<td class='buyPrice'>".$value["buyPrice"]."</td>";
//echo '<td>'.$value["QtySold"].'</td>';
echo "<td class='image'><img src='".$imgDir.$value['image']."' height='100' width='100'/></td>";
//echo '<td>'.$value["ABV"].'</td>';
echo "</tr>";
}
}
echo "</tbody>";
echo "</table>";
?>
</div>
<script type="text/javascript">
var options = {
valueNames: [ 'pName', 'pLine', 'pScale', 'pDes', 'buyPrice','image' ]
};
var userList = new List('tables', options);</script>
</div>
</div>
</body>
</html>
So this is my code. I am trying to filter the table as I am typing into the text box. Any help appreciated.
I've tried following the tutorials but they do not seem to work at all... any ideas?
I find it difficult to understand and apply to my own website, the code I have for filtering is taken from the internet is well.
As I see you're using jQuery so why not use contains selector? You could use it after keyUp event on select tag:
$("#search").keyup(function(){
var search = this.value;
$('#table tr, #table th').show();
$('#table td:contains('+search+')').each(function(){
$(this).parent().hide();
});
});
This code will hide any cell parent (tr, th...) which have a child td containing input value . You can use this code and make it fits better your needs.
Fiddle example: http://jsfiddle.net/uby9quLo/2/
Hope it helps!
I have a bunch locker numbers in a drop down list (populated from MYSQL/PHP). I want to display the locker's combination and location when you select a locker number from the list in two input fields below on the same page.
I have used jquery to tell me which item in the list is selected dynamically. Then I used the $.ajax() function to send that item to my server.
My problem: Can I use $.ajax() to send my variable to the same page I am on? I have tried this and I get an error. I am not sure how to accomplish this. My knowledge of AJAX is very minimal.
My code is as follows:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Locker Backend</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/css" href="form.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
function show()
{
$('#addlocker').toggle();
}
function lockerSelected(sel)
{
var selected = (sel.options[sel.selectedIndex].text);
$.ajax({
type:"POST",
url: "studentdata.php",
data: selected,
success: function(){
alert(selected);
}
});
}
</script>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<?php
$url = $_SERVER['REQUEST_URI'];
$studID = substr($url, strpos($url, "=") + 1);
$db_handle = mysql_connect("localhost", "root", "pickles") or die("Error connecting to database: ".mysql_error());
mysql_select_db("lockers",$db_handle) or die(mysql_error());
$result = mysql_query("SELECT * FROM students WHERE studID = $studID");
?>
<div class="container">
<header> <img src="images/headmast.png" alt="Insert Logo Here" width="686" height="180" id="Insert_logo" /> </header>
<div id="data1">
<form id ="studData" name="studData" action="update.php" medthod="post">
<fieldset>
<legend>Student Details</legend>
<?php
while($row = mysql_fetch_array($result))
{
echo '<ol>';
echo '<li>';
echo '<label for=studid>Student ID</label>';
echo '<input id=studid name=studid type=text value='.$row['studID'].'>';
echo '</il>';
echo '<li>';
echo '<label for=fname>First Name</label>';
echo '<input id=fname name=fname type=text value='.$row['firstName'].'>';
echo '</il>';
echo '<li>';
echo '<label for=fname>Last Name</label>';
echo '<input id=lname name=lname type=text value='.$row['lastName'].'>';
echo '</il>';
echo '<li>';
echo '<label for=email>Email</label>';
echo '<input id=email name=email type=text value='.$row['email'].'>';
echo '</il>';
echo '<li>';
echo '<label for=progam>Program</label>';
echo '<input id=progam name=progam type=text value='.$row['program'].'>';
echo '</il>';
echo '</ol>';
$program = $row['program']; //get name of program
}
?>
<input type="submit" value="Update" class="fButton"/>
</fieldset>
</form>
<form id="locker" name="locker" action="" method="post" >
<fieldset>
<input type="button" onclick="show()" value="Add Locker"/>
<div id="addlocker" style="display:none;">
<!--
query lockers where $program = program parsed in & student id is equal to 0 (this makes it available)
get select list to 10
populate select list --> <br/>
<legend>Lockers Available: </legend>
<select size="10" name="lockerSelect" multiple="yes" style="width:200px;" onChange="lockerSelected(this);">
<?php
$result1=mysql_query("SELECT * FROM lockers WHERE progName = '$program' && studID = 0") or die($result1."<br/><br/>".mysql_error());
while($row1 = mysql_fetch_array($result1))
{
echo '<option value=\"'.$row1['lockerScan'].'">'.$row1['lockerNo'].'</option>';
}
echo '</select>';
echo '<br>';
$lockerNo = $_POST['selected']; \\doesn't work - displays error
echo $lockerNo; \\errors out
?>
</div><!--end of add locker section-->
</fieldset>
</form>
</div><!--end of data1 -->
Search
</div><!-- end of container-->
</body>
</html>
Firstly, you can use :
function show()
{
$('#addlocker').toggle();
}
Then, you should learn more about Ajax and PHP. Your call shoud be :
var selected = (sel.options[sel.selectedIndex].text);
$.ajax({
type:"POST",
url: "studentdata.php",
data: {selected: selected},
success: function(data){
alert(data);
}
});
And in your PHP file :
<?php
$select = $_POST['selected'];
//....
// Do what you have to do then return your result
echo '<div>Send to your page !</div>';
First Arrange your files.
js's is in js folder
php's in php folder
best way is to assaign a seperate php page and then in js use on change event
$(document).on("change", "#selectfieldid", function(){
var selected = $('#selectfieldid').val();
$.ajax({
type:"POST",
url: "studentdata.php",
data: selected,
success: function(data){
$('#addlocker').val(data); //echoed result placed here that has id addlocker
}
});
});
send those to a php page echo the result in that php.