I am trying to do a pagination for category result page which is listing articles with ajax.
I use where clause and need to pass article id to the ajax page.
My codes : ajax.php
include_once '../db.php';
include_once '../class/Articles.php';
$ArticleHandler = new Articles($pdo);
if (!(isset($_GET['pageNumber']))) {
$pageNumber = 1;
} else {
$pageNumber = $_GET['pageNumber'];
}
$perPageCount = 5;
$catid = $_POST['article_id'];
$sql = "SELECT * FROM posts WHERE pcat = ?";
$posts = $ArticleHandler->getPosts($sql, [$catid])->fetchAll();
if ($posts !== '0') {
$rowCount = $ArticleHandler->getPosts("SELECT count(*) FROM posts")->fetchColumn();
}
$pagesCount = ceil($rowCount/$perPageCount);
$lowerLimit = ($pageNumber - 1) * $perPageCount;
$sql = "SELECT * FROM posts WHERE pcat = :pcat ORDER BY pid DESC LIMIT :offset, :limit";
$results = $ArticleHandler->getPosts($sql, array(':pcat'=>$catid, ':offset'=>$lowerLimit, ':limit'=>$perPageCount))->fetchAll();
?>
<table class="table table-hover table-responsive">
<tr>
<th align="center">Name</th>
<th align="center">Experience<br>(in years)
</th>
<th align="center">Subject</th>
</tr>
<?php foreach ($results as $data) { ?>
<tr>
<td align="left"><?php echo $data['ptitle'] ?></td>
</tr>
<?php
}
?>
</table>
<div style="height: 30px;"></div>
<table width="50%" align="center">
<tr>
<td valign="top" align="left"><?php echo $catid; ?></td>
<td valign="top" align="center">
<?php
for ($i = 1; $i <= $pagesCount; $i ++) {
if ($i == $pageNumber) {
?>
<?php echo $i ?>
<?php
} else {
?>
<a href="javascript:void(0);" class="pages"
onclick="showRecords('<?php echo $perPageCount; ?>', '<?php echo $i; ?>');"><?php echo $i ?></a>
<?php
}
}
?>
</td>
<td align="right" valign="top">
Page <?php echo $pageNumber; ?> of <?php echo $pagesCount; ?>
</td>
</tr>
</table>
And index.php
<div id="results"></div>
<div id="loader"></div>
Ajax codes :
function showRecords(perPageCount, pageNumber) {
$.ajax({
type: "GET",
url: "modules/ajax.php",
data: "pageNumber=" + pageNumber,
cache: false,
beforeSend: function() {
$('#loader').html('<img src="loader.png" alt="reload" width="20" height="20" style="margin-top:10px;">');
},
success: function(html) {
$("#results").html(html);
$('#loader').html('');
}
});
}
$(document).ready(function() {
showRecords(10, 1);
});
My tries : I've added a div with artcile id to index.php and used attr to pass it to ajax but couldn't pass it to the page.
Try passing the article id along with pageNumber that you are passing in GET request.
data: {pageNumber : YOUR_PAGE_NUMBER, articleId: ARTICLE_ID}
Do not forget to pass the articleId as 3rd parameter to the function.
Related
Hello Every One i have small problem i will upload multiple images single input file and database store with comma i will stored but i have problem is remove the uploaded images selected and remove the image when we click the image above delete icon that only image deleted
My Code for Retrieve the Multiple images
<div class="panel-body">
<div class="table-responsive">
<table id="dataTableExample1" class="table table-striped table-bordered">
<thead>
<tr>
<th>S.No</th>
<th>Gallery Images</th>
<th>Gallery Name</th>
<th>Operation</th>
</tr>
</thead>
<tbody>
<?php
extract($_REQUEST);
$sql="SELECT * FROM `smw_gallery`";
$result = $conn->query($sql);
$count=$result->num_rows;
if ($count > 0) {
$i=1;
while ($row = $result->fetch_object()) {
$primages = $row->smw_gallery_images;
$imgp = explode(",", $primages);
$realPath = '../assets/images/gallery/';
?>
<tr>
<td style="width:10%"><?=$i;?></td>
<td style="width:50%">
<?php foreach($imgp as $img)
{
echo '<a class="example-image-link" href="#" data-lightbox="example-set" data-title="Click the right half of the image to move forward."><img class="example-image" src="'.$realPath.'/'.$img.'" alt="" height="80" width="80" style="margin: 10px;"/></a>';
} ?>
</td>
<td style="width:10%">
<?php
$limit = 30;
$td_title1 = $row->smw_gallery_name;
if (strlen($td_title1) > $limit)
$td_title1 = substr($td_title1, 0, strrpos(substr($td_title1, 0, $limit), ' '))."...";
echo $td_title1;
?></td>
<td style="width:20%">
<center>
<i class="fa fa-pencil-square-o btn btn-warning" aria-hidden="true"></i>
</center>
</td>
</tr>
<?php $i++; } } ?>
</tbody>
</table>
</div>
</div>
the above code Output look like this
each image i will place delete button and hole gallery delete button
how to made to single image delete button and remove that image only remain will be as it is display
You can do it with small help of jquery, ajax and mysql.
On click delete icon you have to make one ajax request with image name and id parameters. Update image name in database using below query. On success ajax response you can remove that image block using jquery.
Html code for image. Just a sample line.
DeleteIcon
Jquery Code
$(document).on('click', '.delete-image', function(){
var $this = $(this);
var imagname = $(this).data('name');
$.post("delete_image.php",
name: imagname,
id: 1
},
function(data, status){
$this.closest(tr).remove(); //Write your remove code for single image
});
})
I have write code is look like this :
<img class="btn-delete" id="photo-<?=$photo_index_key;?>" data-id="<?=$photo_index_key;?>" data-name="<?=$photo_name;?>" style="margin: 3px 1px 74px -17px; cursor: pointer;" src="../assets/images/closes.png";>
each one of indexkey value can taken in jquery var $imageId = $(this).attr('id');
<script>
$(document).on('click', '.btn-delete', function(){
var imageId = $(this).attr('data-id');
var imageName = $(this).attr('data-name');
var dataString = {id:imageId, name: imageName}
$.ajax({
type: "POST",
url: "remove.php",
data: dataString,
cache: false,
success: function(html){
$('#photo'+imageId).remove(); // you can write your logic
}
});
});
</script>
remove.php
//get ajax data:
$id = $POST['id'];
$name = $POST['name'];
UPDATE smw_gallery
SET `smw_gallery_images` = REPLACE(`smw_gallery_images`, $name,'')
WHERE `id` = $id;
What if you do it in appearance.
That is, you can define the array by indexes
<div class="panel-body">
<div class="table-responsive">
<table id="dataTableExample1" class="table table-striped table-bordered">
<thead>
<tr>
<th>S.No</th>
<th>Gallery Images</th>
<th>Gallery Name</th>
<th>Operation</th>
</tr>
</thead>
<tbody>
<?php
extract($_REQUEST);
$sql = "SELECT * FROM `smw_gallery`";
$result = $conn->query($sql);
$count = $result->num_rows;
if ($count > 0) {
$i = 1;
while ($row = $result->fetch_object()) {
$primages = $row->smw_gallery_images;
$imgp = explode(",", $primages);
$realPath = '../assets/images/gallery/';
?>
<tr>
<td style="width:10%"><?= $i; ?></td>
<td style="width:50%">
<?php foreach ($imgp as $photo_index_key => $img) {
echo '<a class="example-image-link" href="#" data-lightbox="example-set" data-title="Click the right half of the image to move forward.">
<img class="example-image" src="' . $realPath . '/' . $img . '" alt="" height="80" width="80" style="margin: 10px;"/>
</a>';
echo "<a href='".$realPath . "/remove.php?smw_gallery_id=" . $row->id . "&photo_index_key=" . $photo_index_key . "'></a>";
} ?>
</td>
<td style="width:10%">
<?php
$limit = 30;
$td_title1 = $row->smw_gallery_name;
if (strlen($td_title1) > $limit)
$td_title1 = substr($td_title1, 0, strrpos(substr($td_title1, 0, $limit), ' ')) . "...";
echo $td_title1;
?></td>
<td style="width:20%">
<div style="text-align: center;">
<a href="gallery-edit.php?edit=<?= $row->smw_gallery_id; ?>" title="Edit"><i
class="fa fa-pencil-square-o btn btn-warning" aria-hidden="true"></i></a>
</div>
</td>
</tr>
<?php $i++;
}
} ?>
</tbody>
</table>
</div>
I don't know English. This was done via google translate
remove.php
<?php
if (!empty($_GET['smw_gallery_id'] && !empty($_GET['photo_index_key']))) {
$sql = sprintf("SELECT `smw_gallery_images` FROM `smw_gallery` WHERE `id` = %d", $_GET['smw_gallery_id']);
$result = $conn->query($sql);
$result->fetch_assoc();
if (!is_null($result) && is_array($result)) {
while ($row = $result->fetch_assoc()) {
$smw_gallery_images = explode(",", $row['smw_gallery_images']);
$new_smw_gallery_images = array_splice($smw_gallery_images, $_GET['photo_index_key'], 1);
$new_smw_gallery_images = implode(',', $new_smw_gallery_images);
$updateSql = sprintf("UPDATE smw_gallery SET `smw_gallery_images` = %s WHERE `id` = %d", $new_smw_gallery_images, $_GET['smw_gallery_id']);
$conn->query($updateSql);
}
}
}
I am using load more button to load content from the database of specific id on the same web page. Here is the code:
<div class="postList col-lg-12">
<legend><h1 style="color:#298208;">Savings Bucks Details</h1> </legend>
<?php
$busi_id = mysqli_real_escape_string($conn, $_SESSION['busi_id']);
if (isset($busi_id)) {
$query = "SELECT * FROM savingsbucks_business WHERE busi_id='$busi_id' ORDER BY sbb_id DESC LIMIT 2";
$result = mysqli_query($conn, $query) or die('Query failed: ' . mysqli_error($conn));
$numrows_savingsbucks = mysqli_num_rows($result);
if ($numrows_savingsbucks == '0') {
echo "<p style='text-align:center; color:#ff4400; margin-top:40px;'>No Data available!</p>";
} else {
?>
<div class="table-responsive">
<table border="1" class="table table-bordered">
<thead>
<th class="consumer_point_text">Shop ID</th>
<th class="consumer_point_text">SenderID</th>
<th class="consumer_point_text">Busi ID</th>
<th class="consumer_point_text">Customer Type</th>
<th class="consumer_point_text">Customer Name</th>
<th class="consumer_point_text">Customer Email</th>
<th class="consumer_point_text">Customer Phone</th>
<th class="consumer_point_text">Two</th>
<th class="consumer_point_text">Five</th>
<th class="consumer_point_text">Ten</th>
<th class="consumer_point_text">Twenty</th>
<th class="consumer_point_text">Fifty</th>
<th class="consumer_point_text">Hundred</th>
<th class="consumer_point_text">Five Hundred</th>
<th class="consumer_point_text">Total Savings Bucks</th>
</thead>
<?php if($numrows_savingsbucks > 0){
while ($row = mysqli_fetch_array($result)) {
$sbb_id = $row['sbb_id'];
$sender_id = $row['sender_id'];
$busi_id = $row['busi_id'];
$type = $row['type'];
$consu_name = $row['consu_name'];
$consu_email = $row['consu_email'];
$consu_phone = $row['consu_phone'];
$two = $row['two'];
$five = $row['five'];
$ten = $row['ten'];
$twenty = $row['twenty'];
$fifty = $row['fifty'];
$hundred = $row['hundred'];
$five_hundred = $row['five_hundred'];
$total_two += $two;
$total_five += $five;
$total_ten += $ten;
$total_twenty += $twenty;
$total_fifty += $fifty;
$total_hundred += $hundred;
$total_five_hundred += $five_hundred;
$total_bucks = $two+$five+$ten+$twenty+$fifty+$hundred+$five_hundred;
$grand_total += $total_bucks;
?>
<tr>
<td class="consumer_point_text"><?=$sbb_id?></td>
<td class="consumer_point_text"><?=$sender_id?></td>
<td class="consumer_point_text"><?=$busi_id?></td>
<td class="consumer_point_text" style="text-transform:capitalize;"><?=$type?></td>
<td class="consumer_point_text"><?=$consu_name?></td>
<td class="consumer_point_text"><?=$consu_email?></td>
<td class="consumer_point_text"><?=$consu_phone?></td>
<td class="consumer_point_text"><?=$two?></td>
<td class="consumer_point_text"><?=$five?></td>
<td class="consumer_point_text"><?=$ten?></td>
<td class="consumer_point_text"><?=$twenty?></td>
<td class="consumer_point_text"><?=$fifty?></td>
<td class="consumer_point_text"><?=$hundred?></td>
<td class="consumer_point_text"><?=$five_hundred?></td>
<td class="consumer_point_text"><?=$total_bucks?></td>
</tr>
<?php } ?>
</table>
<div class="show_more_main" sbb_id="show_more_main<?php echo $sbb_id; ?>">
<span sbb_id="<?php echo $sbb_id; ?>" class="show_more" title="Load more posts">Load more</span>
<span class="loding" style="display: none;"><span class="loding_txt">Loading...</span></span>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script
<script src="http://demos.codexworld.com/includes/js/bootstrap.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('sbb_id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'ajax_more_business_shop.php',
data:'sbb_id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('.postList').append(html);
}
});
});
});
</script>
<?php } ?>
</div> <!-- ./col-lg-12 -->
<?php } }?>
On this page its displaying 2 results which have common busi_id (WHERE busi_id=$busi_id), when I click on load more button, its displaying others content too which don't have same "busi_id" as on this page showing first 2 results.
Here is ajax page:
ajax_more_business_shop.php :
<?php
ini_set('error_reporting', E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
if(!empty($_POST["sbb_id"])) {
require_once ('admin/includes/config.php');
$query = "SELECT COUNT(*) as num_rows FROM savingsbucks_business WHERE sbb_id < ".$_POST['sbb_id']." ORDER BY sbb_id DESC";
$result = mysqli_query ($conn, $query);
$row = mysqli_fetch_assoc($result);
$totalRowCount = $row['num_rows'];
$busi_id = $row['busi_id'];
$showLimit = 2;
$query = "SELECT * FROM savingsbucks_business WHERE sbb_id < ".$_POST['sbb_id']." ORDER BY sbb_id DESC LIMIT $showLimit";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$rowcount=mysqli_num_rows($result);
?>
<table border="1" class="table table-bordered">
<?php
if ($rowcount > '0') {
while($row = mysqli_fetch_assoc($result))
{
$sbb_id = $row['sbb_id'];
$sender_id = $row['sender_id'];
$busi_id = $row['busi_id'];
$type = $row['type'];
$consu_name = $row['consu_name'];
$consu_email = $row['consu_email'];
$consu_phone = $row['consu_phone'];
$two = $row['two'];
$five = $row['five'];
$ten = $row['ten'];
$twenty = $row['twenty'];
$fifty = $row['fifty'];
$hundred = $row['hundred'];
$five_hundred = $row['five_hundred'];
$total_two += $two;
$total_five += $five;
$total_ten += $ten;
$total_twenty += $twenty;
$total_fifty += $fifty;
$total_hundred += $hundred;
$total_five_hundred += $five_hundred;
$total_bucks = $two+$five+$ten+$twenty+$fifty+$hundred+$five_hundred;
$grand_total += $total_bucks;
?>
<tr>
<td class="consumer_point_text"><?=$sbb_id?></td>
<td class="consumer_point_text"><?=$sender_id?></td>
<td class="consumer_point_text"><?=$busi_id?></td>
<td class="consumer_point_text"><?=$type?></td>
<td class="consumer_point_text"><?=$consu_name?></td>
<td class="consumer_point_text"><?=$consu_email?></td>
<td class="consumer_point_text"><?=$consu_phone?></td>
<td class="consumer_point_text"><?=$two?></td>
<td class="consumer_point_text"><?=$five?></td>
<td class="consumer_point_text"><?=$ten?></td>
<td class="consumer_point_text"><?=$twenty?></td>
<td class="consumer_point_text"><?=$fifty?></td>
<td class="consumer_point_text"><?=$hundred?></td>
<td class="consumer_point_text"><?=$five_hundred?></td>
<td class="consumer_point_text"><?=$total_bucks?></td>
</tr>
<?php }
?>
</table>
<?php if($totalRowCount > $showLimit){ ?>
<div class="show_more_main" sbb_id="show_more_main<?php echo $sbb_id; ?>">
<span sbb_id="<?php echo $sbb_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>
<?php } ?>
<?php
}
}
?>
I want, when i click "load more button", It must show/load 2 more row of content where busi_id will be common, I mean if busi_id=69, it should show/load only 2 more content/result from database which have busi_id 69, not other data with different busi_id.
I tried to explain,
Thank you.
I have just passed the "busi_id" to Ajax page... with load more button..
<div class="show_more_main" ds_id="show_more_main<?php echo $ds_id; ?>">
<span ds_id="<?php echo $ds_id; ?>" busi_id="<?php echo $busi_id; ?>" class="show_more" title="Load more posts">Load more</span>
<span class="" style="display: none;"><span class="loding_txt">Loading...</span></span>
</div>
And..
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('ds_id');
var Busi_id = $(this).attr('busi_id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'ajax_more_consumer_shop.php',
data: {
'ds_id': ID,
'busi_id': Busi_id
},
success:function(html){
$('#show_more_main'+ID).remove();
$('.postList').append(html);
}
});
});
});
on ajax_more_business_shop.php....
$query = "SELECT COUNT(*) as num_rows FROM savingsbucks_business WHERE ds_id < ".$_POST['ds_id']." AND busi_id=".$_POST["busi_id"]." ORDER BY ds_id DESC";
$result = mysqli_query ($conn, $query);
$row = mysqli_fetch_assoc($result);
$totalRowCount = $row['num_rows'];
$showLimit = 2;
$query = "SELECT * FROM savingsbucks_business WHERE ds_id < ".$_POST['ds_id']." AND busi_id=".$_POST["busi_id"]." ORDER BY ds_id DESC LIMIT $showLimit";
$result = mysqli_query ($conn, $query);
$rowcount=mysqli_num_rows($result);
Modified the query.. and get the desired output.
Thanks!
Basically, I have a list of categories that I am iterating form mysqli
<div style="width:20%; float:left;">
<h3>Categories</h3>
<?php while($categories = $resultproductcategories->fetch_assoc()){?>
<div class="rows">
<input type="button" name="<?php echo $categories['id'] ?>" value="<?php echo $categories['category?>" />;
</div>
<?php }?>
</div>
Now what I want that if I press any category it should fetch data accordingly there is my code for fetching
$stmtproducts = $mysqli->prepare("SELECT * FROM store_products sp INNER JOIN store_product_categories spc ON sp.product_category=spc.id WHERE sp.store_id=? AND sp.category=? LIMIT $count, 10");
$stmtproducts->bind_param("ii",$_SESSION['storeid'],$_POST['']);
$stmtproducts->execute();
$resultproducts = $stmtproducts->get_result();
$num=$resultproducts->num_rows;
echo $num;
$stmtproducts->close();
I am confused that if there was a specific name of input then I would have gotten it by isset($_POST['name']) but there is no specific name... I cannot think of how to send category to mysql.
<div id="divTransactional" style="width:70%;padding-left:5%; float:left;">
<?php if($num>0) {?>
<table class="table table-responsive table-hover" id="tableProducts">
<h3>Products</h3>
<tbody>
<?php for($i=0;$i<$num;$i++) { $products = $resultproducts->fetch_assoc();//while($products = $resultproducts->fetch_assoc()) {?>
<tr>
<td>Code: <?php echo $products['product_code'];?></td><td>Added On: <?php echo $products['product_date'];?></td>
</tr>
<tr>
<td>Name: <?php echo $products['product_name'];?></td>
</tr>
<tr>
<td>Category: <?php echo $products['category'];?></td>
</tr>
<tr>
<td>Description: <?php echo $products['product_desc'];?></td>
</tr>
<tr>
<td>Price: <?php echo $products['product_price'];?></td><td>Discount: <?php echo $products['product_discount'];?></td>
</tr>
<tr style="width:100px; height:100px;">
<td><img src="../../uploads/store/products/<?php echo $products['product_image1'];?>" style="width:100px; height:100px;"/></td>
<td><img src="../../uploads/store/products/<?php echo $products['product_image2'];?>" style="width:100px; height:100px;"/></td>
<td><img src="../../uploads/store/products/<?php echo $products['product_image3'];?>" style="width:100px; height:100px;"/></td>
<td><img src="../../uploads/store/products/<?php echo $products['product_image4'];?>" style="width:100px; height:100px;"/></td>
</tr>
<?php }?>
</tbody>
<?php if($num >= 10) { ?>
Next
<?php } ?>
<?php $prev = $count - 10;
if ($prev >= 0){?>
Previous
<?php }?>
</table>
<?php if($num >= 10) { ?>
Next
<?php } ?>
<?php $prev = $count - 10;
if ($prev >= 0){?>
Previous
<?php }?>
<?php } ?>
</div>
I would suggest using Ajax to call the server with an Id in parameters.
You need to add a class to your buttons and you do need to link a JS file and JQuery. here's an example.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="path/to/your/file.js"></script>
<div style="width:20%; float:left;">
<h3>Categories</h3>
<?php while($categories = $resultproductcategories->fetch_assoc()){?>
<div class="rows">
<input type="button" name="<?php echo $categories['id'] ?>" value="<?php echo $categories['category']?>" class="btnCategory"/>;
</div>
<?php }?>
And then, using ajax you can call your php file that returns the value you need to fetch from your database.
$(document).ready(function() {
$('.btnCategory').on('click', function(){
var id = $this.attr('name');
$.ajax({
url: 'path/to/your/file.php',
method: "GET",
data: {category_id: id},
success: function(data) {
//This is the data fetch from the server
console.log(data);
},
error: function(err) {
console.error('An error occurred : ' + err);
}
});
});
});
And then, when your PHP file receive the parameter $_GET['category_id'] you call your database.
<?php
if(isset($_GET['category_id'])){
//An id was post in the url.
$stmtproducts = $mysqli->prepare("SELECT * FROM store_products sp INNER JOIN store_product_categories spc ON sp.product_category=spc.id WHERE sp.store_id=? AND sp.category=? LIMIT $count, 10");
$stmtproducts->bind_param("ii",$_SESSION['storeid'],$_POST['']);
$stmtproducts->execute();
$resultproducts = $stmtproducts->get_result();
$num=$resultproducts->num_rows;
$stmtproducts->close();
$result = array('row_count' => $num, 'result' => $resultproducts);
echo json_encode($result);
}
And then you return a json array of your result. That's what I would do.
Hope it helps !
Nic
You asked for a demo, here it is .
<?php
if(isset($_GET['category_id'])){
//An id was post in the url.
$stmtproducts = $mysqli->prepare("SELECT * FROM store_products sp INNER JOIN store_product_categories spc ON sp.product_category=spc.id WHERE sp.store_id=? AND sp.category=? LIMIT $count, 10");
$stmtproducts->bind_param("ii",$_SESSION['storeid'],$_POST['']);
$stmtproducts->execute();
$resultproducts = $stmtproducts->get_result();
$num=$resultproducts->num_rows;
$stmtproducts->close();
$result = array('row_count' => $num, 'result' => $resultproducts);
echo json_encode($result);
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div style="width:20%; float:left;">
<h3>Categories</h3>
<?php while($categories = $resultproductcategories->fetch_assoc()){?>
<div class="rows">
<input type="button" name="<?php echo $categories['id'] ?>" value="<?php echo $categories['category']?>" class="btnCategory"/>;
</div>
<?php }?>
</div>
<script>
$(document).ready(function() {
$('.btnCategory').on('click', function(){
var id = $this.attr('name');
$.ajax({
method: "GET",
data: {category_id: id},
success: function(data) {
//This is the data fetch from the server
console.log(data);
},
error: function(err) {
console.error('An error occurred : ' + err);
}
});
});
});
</script>
I'm using keypress via this OOP function below to update my sites shopping cart and quantity value. Sometimes it works, but most of the time when I press the enter key it doesn't a) update the cart nor b) update the qty value. I think it's refreshing the page, which could be the issue.
I took a look at the request header value by inspecting the qty element and that doesn't update when enter key pressed, if that helps.
function initBinds() {
if ($('.remove_basket').length > 0) {
$('.remove_basket').bind('click', removeFromBasket);
}
if ($('.update_basket').length > 0) {
$('.update_basket').bind('click', updateBasket);
}
if ($('.fld_qty').length > 0) {
$('.fld_qty').bind('keypress', function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code == 13) {
updateBasket();
}
});
}
}
And here's the updateBasket function
function updateBasket() {
$('#frm_basket :input').each(function() {
var sid = $(this).attr('id').split('-');
var val = $(this).val();
$.ajax({
type: 'POST',
url: '/mod/basket_qty.php',
data: ({ id: sid[1], qty: val }),
success: function() {
refreshSmallBasket();
refreshBigBasket();
},
error: function() {
alert('An error has occurred');
}
});
});
}
And, this is the page...
Note, you can see on line 41 the class of fld_qty is used for the initiBinds keypress function if statement.
<?php
$session = Session::getSession('basket');
$objBasket = new Basket();
$out = array();
if (!empty($session)) {
$objCatalogue = new Catalogue();
foreach ($session as $key => $value) {
$out[$key] = $objCatalogue->getProduct($key);
}
}
require_once('_header.php'); ?>
<div id="cat_prod"><h1>- BASKET -</h1></div>
<?php
if (!empty($out)) { ?>
<div id="big_basket">
<form action="" method="post" id="frm_basket">
<table cellpadding="0" cellspacing="0" border="0" class="tbl_repeat">
<tbody id="basket_table">
<tr style="background-color: #f2f3ee;">
<th class="ta_left">Item</th>
<th class="ta_r">Qty</th>
<th class="ta_r col_15">Price</th>
<th class="ta_r col_15"></th>
</tr>
<?php foreach ($out as $item) { ?>
<tr>
<td class="ta_left_name"><?php echo Helper::encodeHTML($item['name']); ?></td>
<td class="ta_left_qty"><input type="text" name="qty-<?php echo $item['id']; ?>"
id="qty-<?php echo $item['id']; ?>" class="fld_qty"
value="<?php echo $session[$item['id']]['qty']; ?>" /></td>
<td class="ta_r">£<?php echo number_format($objBasket->itemTotal($item['price'], $session[$item['id']]['qty']), 2); ?></td>
<td class="ta_r"> <?php echo Basket::removeButton($item['id']); ?></td>
</tr>
<?php } ?>
<?php if ($objBasket->_vat_rate != 0) { ?>
<tr style="border-bottom: dashed 1px #aaa">
<td class="ta_left" colspan="2">Sub-total :</td>
<td class="ta_r bt_td">£<?php echo number_format($objBasket->_sub_total, 2); ?></td>
<td class="ta_r bt_td"> </td>
</tr>
<tr style="border-bottom: dashed 1px #aaa">
<td class="ta_left" colspan="2">VAT (<?php $objBasket->_vat_rate; ?>%) :</td>
<td class="ta_r bt_td">£<?php echo number_format($objBasket->_vat, 2); ?></td>
<td class="ta_r bt_td"> </td>
</tr>
<?php } ?>
<tr>
<td class="ta_right" colspan="2"><strong>Total :</strong></td>
<td class="ta_r bt_td">£<?php echo number_format($objBasket->_total, 2); ?></td>
<td class="ta_r bt_td"> </td>
</tr>
</tbody>
</table>
<div class="dev br_td"> </div>
<div class="dev br_td"> </div>
<div class="sbm sbm_blue fl_r">
Checkout
</div>
<div class="sbm sbm_blue fl_l update_basket">
<span class="btn">Update</span>
</div>
</form>
</div>
<?php } else { ?>
<br />
<br />
<p><em>Your basket is currently empty.</em></p>
<?php } ?>
<?php require_once('_footer.php'); ?>
I have looked through some statckflow pages regarding this and have tried keydown and just using e.which and e.keyCode || e.which instead, but they all render the same issue of not working 100% of the time when you press enter key.
I understand some browsers may not support this, so is there a better approach for this operation? I have tested Firefox, Chrome and Safari (all latest).
Thanks for the help, appreciated! :)
Edit;
Here's the mod/basket_qty.php also...
<?php
require_once('../inc/autoload.php');
if (isset($_POST['qty']) && isset($_POST['id'])) {
$out = array();
$id = $_POST['id'];
$val = $_POST['qty'];
$objCatalogue = new Catalogue();
$product = $objCatalogue->getProduct($id);
if (!empty($product)) {
switch($val) {
case 0:
Session::removeItem($id);
break;
default:
Session::setItem($id, $val);
}
}
}
Looks like I needed to add e.preventDefault(); in the initBinds function for if (code == 13) { as pointed out by cmorrissey. It seems to be working fine with this. Thanks!!
I have made a script for Pagination and it can be displayed.
I will be a problem when the Next Button is pressed, the Pagination can't continue to the next page.
when the url has changed but the page remains in the first place.
eg:
[1]. http:// localhost /pagination/
This works and can display data 1-10 on page 1.
[2] http:// localhost /pagination/?page=2
paging should've been on page 2, but the data shown is 1-10 (supposedly 11-20)
This is the code:
// data_students.php
<?php
require 'conn.php';
open_conn();
?>
<table class="table table-condensed table-bordered table-hover" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th style="width:20px">No</th>
<th style="width:120px">NIM</th>
<th style="width:200px">Name</th>
<th>Address</th>
<th style="width:120px">Room</th>
<th style="width:120px">Status</th>
<th style="width:40px"></th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
$num_pages = 10;
$num_data = mysql_num_rows(mysql_query("SELECT * FROM students"));
$total_page = ceil($num_data / $num_pages);
// query searching
if(isset($_POST['search'])) {
$key = $_POST['search'];
echo "<strong>Search results for keyword: $key</strong>";
$query = mysql_query("
SELECT * FROM students
WHERE nim LIKE '%$key%'
OR name LIKE '%$key%'
OR address LIKE '%$key%'
OR room LIKE '%$key%'
OR status LIKE '%$key%'
");
// query if the specified page number
} elseif(isset($_GET['page']) && $_GET['page']!="") {
$page = $_GET['page'];
$i = ($page - 1) * $num_pages + 1;
$query = mysql_query("SELECT * FROM students ORDER BY name ASC LIMIT ".(($page - 1) * $num_pages).", $num_pages");
// query when there is no parameter page and search
} else {
$query = mysql_query("SELECT * FROM students ORDER BY name ASC LIMIT 0, $num_pages");
}
// show database students
while($data = mysql_fetch_array($query)) {
if($data['status']==1) {
$status = "Active";
} else {
$status = "Off";
}
?>
<tr>
<td><?php echo $i ?></td>
<td><?php echo $data['nim'] ?></td>
<td><?php echo $data['name'] ?></td>
<td><?php echo $data['address'] ?></td>
<td><?php echo $data['room'] ?></td>
<td><?php echo $status ?></td>
<td>
<a href="#dialog-students" id="<?php echo $data['kd_mhs'] ?>" class="change" data-toggle="modal">
<i class="icon-pencil"></i>
</a>
<a href="#" id="<?php echo $data['kd_mhs'] ?>" class="delete">
<i class="icon-trash"></i>
</a>
</td>
</tr>
<?php
$i++;
}
?>
</tbody>
</table>
<?php if(!isset($_POST['search'])) { ?>
<!-- to display the menu page -->
<div class="pagination pagination-right">
<ul>
<?php for($i = 1; $i <= $total_page; $i++) { ?>
<li class="page" id="<?php echo $i ?>"><?php echo ''.$i.'' ;?></li>
<?php } ?>
</ul>
</div>
<?php } ?>
<?php
close_conn();
?>
this is jquery:
// students-app.js
(function($) {
// function is executed after the entire document is displayed
$(document).ready(function(e) {
var kd_mhs = 0;
var main = "data_students.php";
// show data students from data_students.php in index.php <div id="data-students"></div>
$("#data-students").load(main);
// when the search inputbox filled
$('input:text[name=searching]').on('input',function(e){
var v_search = $('input:text[name=searching]').val();
if(v_search!="") {
$.post(main, {search: v_search} ,function(data) {
$("#data-students").html(data).show();
});
} else {
$("#data-students").load(main);
}
});
// when the button page is pressed
$('.page').live("click", function(event){
// take the value of the inputbox
kd_page = this.id;
$.post(main, {page: kd_page} ,function(data) {
$("#data-students").html(data).show();
});
});
});
}) (jQuery);