I'm building a shopping site in PHP with mysqli database and I have a "category" and a "brands" sections in that.
What I want is that the user can filter the products in the store by clicking on category & brands section without page refreshing with help of ajax jQuery.
For example on Category>Electronics and it will show him the Electronics products on site main page.
Maybe with the code, it will be clearer.
This is the part of the HTML:
<div class="panel panel-info">
<div class="panel-heading">Products</div>
<div class="panel-body">
<div id="getProduct"></div>
</div>
This is the PHP code in the "action.php" file:
<?php
if(isset($_POST["getSelectedCategory"])){
$cid=$_POST["categoryID"];
$sql="SELECT * FROM products WHERE productCat = '$cid' ";
$run_query=mysqli_query($con, $sql);
while($row=mysqli_fetch_arry($run_query)){
$productID = $row["productID"];
$productCat = $row["productCat"];
$productBrand = $row["productBrand"];
$productTitle = $row["productTitle"];
$productPrice = $row["productPrice"];
$productIMG = $row["productIMG"];
echo " <div class='col-md-4'>
<div class='panel panel-info'>
<div class='panel-heading'>$productTitle</div>
<div class='panel-body'>
<img src='assets/$productIMG' style='width: 160px; height: 250px;'/>
</div>
<div class='panel-heading'>$productPrice.00$
<button pid='$productID' style='float: right;' class='btn btn-danger btn-xs'>Add To Cart</button>
</div>
</div>
</div> ";
}
}
?>
This is the jQuery code:
$("body").delegate(".category","click",function (event) {
event.preventDefault();
var cid = $(this).attr("categoryID");
/*Used this alert to see if the
right category number is shown, Here it says undefined*/
alert(cid);
$.ajax({
url: "action.php",
method: "POST",
data: {getSelectedCategory: 1, categoryID: cid},
success: function (data){
$("#getProduct").html(data);
}
})
});
I can't seem to find the problem in my code.
You js code is listening to .category class. And there is no such class in your php code template. That's how your echo should look like to work:
echo " <div class='col-md-4'>
<div class='panel panel-info'>
<div class='panel-heading'>$productTitle</div>
<div class='panel-body'>
<img src='assets/$productIMG' style='width: 160px; height: 250px;'/>
</div>
<div class='panel-heading'>
<a class='category' categoryID = '$productCat'>$productBrand</a>
$productPrice.00$
<button pid='$productID' style='float: right;' class='btn btn-danger btn-xs'>Add To Cart</button>
</div>
</div>
</div> ";
Look - I've added <a class="category" categoryID = '$productCat'>$productBrand </a> to you panel-header.
Related
My code works fine, it displays more users when the load more button is clicked.
my constraint right now is how to remove the Load more button if there is no more value on the response.
This is how my model looks like
public function getFreeAds($page){
$offset = 10*$page;
$limit = 10;
$this->db->select('*');
$this->db->from('escort');
$this->db->where('status', 'Approved');
$this->db->limit($offset ,$limit);
$this->db->order_by("time_stamp, UPPER(time_stamp)", "DESC");
$query = $this->db->get();
return $query->result();
}
My Controller looks like this
public function getCountry(){
$page = $_GET['page'];
$countries = $this->Home_model->getCountry($page);
foreach($countries as $country){
echo
'<div class="col-md-4 col-sm-6">
<div class="portfolio-item">
<div class="thumb">
<a ><div class="hover-effect" data-e_id="'.$country->e_id.'" id="profile2">
<div class="hover-content">
<h1> '.$country->ProfileName.'</em></h1>
<p> '.$country->Height.' CM tall '.$country->BreastCup.' Breast Size <b>Nationality: '.$country->Nationality.' </b></p>
<button type="button" class="btn-info">View More</button>
<button type="button" class="'.$country->confirmstatus.'">'.$country->confirmstatus.'</button>
<div class="top">
</div>
</div>
</div></a>
<div class="image" width="70%" height="1000px">
<img src="uploads/'.$country->ProfilePicture.'">
</div>
</div>
</div>
</div>';
}
exit;
}
Here is my query code that displays the response.
$(document).ready(function(){
getcountry(0);
$("#load_more").click(function(e){
e.preventDefault();
var page = $(this).data('val');
getcountry(page);
});
});
var getcountry = function(page){
$("#loader").show();
$.ajax({
url:"<?php echo base_url() ?>Home/getCountry",
type:'GET',
data: {page:page}
}).done(function(response){
$("#show_data").append(response);
$("#loader").hide();
$('#load_more').data('val', ($('#load_more').data('val')+1));
scroll();
});
};
var scroll = function(){
$('html, body').animate({
scrollTop: $('#load_more').offset().top
}, 1000);
};
What you can do is get the next values in the same function and if there are values available you can make an input field(hidden) and then show or hide the button according to its value.
I'm writing a possible solution for your case, comments are mentioned wherever necessary. Remember there are better ways of doing this like using count but this is according to your code. See if it helps you.
Controller
public function getCountry(){
$page = $_GET['page'];
$countries = $this->Home_model->getCountry($page);
$nextValue = $this->Home_model->getCountry($page+1); // get the values for the next page
$showButton = !empty($nextValue) ? 'yes' : 'no'; // show the button if next value exists
foreach($countries as $country){
echo
'<div class="col-md-4 col-sm-6">
<div class="portfolio-item">
<div class="thumb">
<a ><div class="hover-effect" data-e_id="'.$country->e_id.'" id="profile2">
<div class="hover-content">
<h1> '.$country->ProfileName.'</em></h1>
<p> '.$country->Height.' CM tall '.$country->BreastCup.' Breast Size <b>Nationality: '.$country->Nationality.' </b></p>
<input type="hidden" class="showButton" value="'.$showButton.'" />
<!-- make a hidden input field and assign a value (yes/no) -->
<button type="button" class="btn-info">View More</button>
<button type="button" class="'.$country->confirmstatus.'">'.$country->confirmstatus.'</button>
<div class="top">
</div>
</div>
</div></a>
<div class="image" width="70%" height="1000px">
<img src="uploads/'.$country->ProfilePicture.'">
</div>
</div>
</div>
</div>';
}
exit;
}
View
var getcountry = function(page){
$("#loader").show();
$.ajax({
url:"<?php echo base_url() ?>Home/getCountry",
type:'GET',
data: {page:page}
}).done(function(response){
$("#show_data").append(response);
$("#loader").hide();
$('#load_more').data('val', ($('#load_more').data('val')+1));
// check the value of input field
if($('.showButton:last').val() == "no"){
$('#load_more').hide(); // hide the button
}
scroll();
});
};
Add to your response metadata with total pages count. During every request make count query to your DB with same clauses. In your JS code after every request compare current page with total pages from response and hide button if last page reached.
After a button is selected on a fresh page, all information are there, but whenever another is clicked, the first info is still there and wont change until the page is refreshed.
Help me pass this will ya?
button
<?php while($b = mysqli_fetch_assoc($equery)): ?>
<button type="button" onclick="modal(<?=$b['id'];?>)" class="w3-btn w3-border" style="width: 260px; display: inline-block; margin: 9px">
<img src="">
<h3><?php echo $b['product'];?></h3>
<h5>Descritopm</h5>
<h6></h6>
</button>
<?php endwhile;?>
js:
function modal(id){
var data = {"id" : id};
jQuery.ajax({
url : <?=BASEURL;?>+'includes/modal.php',
method : "post",
data : data,
success: function(data){
jQuery('body').append(data);
jQuery('#mod').modal('show');
},
error: function(){
alert("IDK")
}
});
}
modal:
<?php
require_once '../core/init.php';
$id = $_POST['id'];
$id =(int)$id;
$sql = "SELECT * FROM aisle WHERE id = '$id'";
$result = $db->query($sql);
$product = mysqli_fetch_assoc($result);
?>
<!-- Modal -->
<?php ob_start();?>
<div id="mod" class="modal fade" role="dialog" tabindex="-1">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title w3-center"><?=$product['product'];?></h3>
</div>
<div class="modal-body">
<p><?=$product['aisle'];?></p>
<p>$<?=$product['price'];?></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<?php echo ob_get_clean();?>
The problem is here
jQuery('body').append(data);
This line will append more modal and many modals will appear on your page. You should follow this way. Create a div tag called contents_from_ajax inside body tag and then use this.
jQuery('#contents_from_ajax').html(data);
This code will remove all old modals and create a new one instead of append, and then it will work fine.
Hope this help
I'm trying to return data of another page and I just get one time.
The result is just for the first, i think the ajax is correct because in the console the data is correct but when will be insert in the modal it happen this error.
PHP:
$sql = $mysqli->prepare("SELECT * FROM users ORDER by registred DESC");
$sql->bind_param("i", $_SESSION["userid"]);
$sql->execute();
$res = $sql->get_result();
if($res->num_rows) {
while($row = $res->fetch_assoc()) {
echo "
<div id='myModal' class='modal fade' role='dialog'>
<div class='modal-dialog'>
<div class='modal-content'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal'>×</button>
<h4 class='modal-title'> Data from user </h4>
</div>
<div class='modal-body' id='add_link_".base64_encode($row["id"])."'>
</div>
<div class='modal-footer'>
<button type='button' class='btn btn-default' data-dismiss='modal'> Close </button>
</div>
</div>
</div>
</div>
";
}
}
Javascript:
<script src="js/jquery.min.js"></script>
<script type='text/javascript'>
function att(id){
$.get("ajax.php?i="+id, function( data ) {
console.log(id);
$("#add_link_" +id).html("");
if($("#add_link_" +id).html(data)) {
console.log(data);
$('#myModal').modal('show');
}
});
}
</script>
You are "showing" #myModal which is supposed to be unique on your page, but it is not. Also, your function is not being called. But, I suppose you are calling it somewhere since you are saying that console.log is showing your correct data.
Basically, change your $('#myModal').modal('show'); call to this:
$(this).closest('.modal').modal('show');
I have a page (menu.php) that retrieves and displays data from a database including name, image, price
I want to add a link when i click on the image take me to another page (single Product.php) , so i have only one page and i want its content depending on the image i have clicked
<div class="row">
<div class="col-md-9">
<div class="products-heading">
<h2>Our Salad</h2>
</div> <!-- End of /.Products-heading -->
<div class="product-grid">
<div class="row">
<?php
require('connection.php');
extract($_POST);
$rc=mysql_query("select * from menu where Item_Catagory = 'Salad'") or die(mysql_error());
while($MenuItem=mysql_fetch_array($rc))
{
?>
<!--To send item info to single-product page -->
<div class="col-md-4">
<div class="products">
<a href="single-product.php" >
<img src="images/<?php echo $MenuItem['Item_Image']; ?>" alt="" />
</a>
<a href="single-product.php">
<h4> <?php echo $MenuItem['Item_Name']?> </h4>
</a>
<p class="price"> <?php echo $MenuItem['Item_Price']?></p>
<div class="row lead">
<center><div id="stars" class="starrr"></div></center>
</div>
<a class="view-link shutter" href="#">
<i class="fa fa-plus-circle"></i>Add To Cart</a>
</div> <!-- End of /.products -->
</div> <!-- End Of /.Col-md-4 -->
<?php }
?>
</div> <!-- End of /.row -->
this is a part of the first page
I want to use get method to send the data to the another page, but i do not what is the appropriate method should i use javascript?if yes how?
Use id's to send data:
<a class="view-link shutter" href="Product.php?id="<?= $MenuItem['id'];?>">
In the other page $dataID = $_GET[id]; than query your DB where id=$dataID
change <a href="single-product.php">
to <a href="single-product.php?name=<?php echo $MenuItem['Item_Name']?>">
An example redirect would now be "single-product.php?name=food"
In single-product.php you could now retrieve the itemname with $_GET (superglobal).
In your script you would get it by $item = $_GET['name'], $item is now equal to 'food'.
To get information about this particular product "food", you query the database in single-product.php like so: "select * from menu where Item_Name = '".$item."'". Now append the result into your html.
To do this by ajax you would need to handle all the anchor tags, assuming you are using jQuery the following will do:
$('a').click(function(){
$.ajax({
url: this.href,
method: 'GET',
success: function(response){
console.log(response);
//here you can append the response to your html
}
});
return false; //prevent browser from redirecting
});
I am making a php chat but am having some trouble using ajax to check a mysql database and to put the data into a div. Here are my codes:
HTML
<div id="chatbox">
<div class="chatheader"><div class="chatheadertext">chatheader</div></div>
<div id="chatcontainer">
<div class="chatpadding">
<div id="chatmessages">
<div class="chat-replies">
<div class="chat-reply-container">
<div class="chat-reply-avatar">
<img src="img/default_avatar.png">
</div>
<div class="chat-reply-chat">
<span class="chat-reply-author">testuser</span><br>
<span class="chat-reply-content">test message goes here</span>
</div>
</div>
</div>
</div>
</div>
<form id="form" action="">
<textarea class="chatchat" id="message" placeholder="Type message here!"></textarea>
</form>
</div>
</div>
JAVASCRIPT
<script>
$(".chatheader").on("click", function () {
$("#chatcontainer").slideToggle();
});
$("textarea").keyup(function(e){
if((e.keyCode ? e.keyCode : e.which) == 13) {
//The enter button has been pressed
}
});
$(function ()
{
$.ajax({
url: 'ajax.php',
data: "",
dataType: 'json',
success: function(data)
{
$('#chatmessages').html("<div class='chat-replies'>
<div class='chat-reply-container'>
<div class='chat-reply-avatar'>
<img src='img/default_avatar.png'>
</div>
<div class='chat-reply-chat'>
<span class='chat-reply-author'>testuser</span><br>
<span class='chat-reply-content'>test message goes here</span>
</div>
</div>
</div>");
}
});
});
</script>
PHP
<?php
$con = mysqli_connect('localhost','root','','chat');
$query = mysqli_query($con,"SELECT * FROM `messages`");
$msgnum = mysqli_num_rows($query);
$array = mysqli_fetch_row($query);
echo json_encode($array);
?>
So basically what I am trying to do is use ajax to contact the php file which will then check the mysql database for tables and encode them to json, on the index page, the chatbox is supposed to come up by the first javascript function but it's not sliding up. know that it is the ajax that is doing this, specifically the $('#chatmessages').html(); line. When I remove the code from that line, the chatbox comes up but is empty inside. What am I doing wrong, how would I do it so that when it contacts, for each row that is found in the database, it echoes
<div class='chat-replies'>
<div class='chat-reply-container'>
<div class='chat-reply-avatar'>
<img src='img/default_avatar.png'>
</div>
<div class='chat-reply-chat'>
<span class='chat-reply-author'>testuser</span><br>
<span class='chat-reply-content'>test message goes here</span>
</div>
</div>
</div>
So if there are like 50 rows in the database, it would echo that script for each of the rows, and there would be an overflow-y:scroll on the <div id="chatmessages"> so it doesn't overflow. Thanks in advance to anyone that can help!
If you've json data in success callback of your AJAX call, you can iterate through all records and append each record to your chat div
success: function(data)
{
$.each(data,function(index,dataRecord){
document.getElementById('chatmessages').innerHTML +="html content goes here";
});
//scroll down your div,make sure you should have propery, overflow-y:scroll
document.getElementById('chatmessages').scrollTop=100000;
}
Hope this will help,
Thanks