I write a script in jquery: "add to cart". The problem is that the above script works, but not as it should be.
When I press the addtobasket div, it does a string of all names and prices. He does not get value only from this div.
I do not know how to do it, only to take it this value of div cenaprzedmiotu and div nazwa.
HTML/PHP (this is my product):
while ($row = $result - > fetch_assoc()) {
$i++;
echo "<div class=\"col-md-3\"><section class = 'produkt'id = '$i'draggable = 'true' > ";
echo "<div class=\"opis\"> <div class = \"nazwa\" style='margin-top:6px;'>".$row['nazwa']."</div> <div > < b > Cena: < /b> <span class=\"cenaprzedmiotu\">".$row['cena']."</span > PLN < /div> <div id = 'kategoriaproduktu'style = 'display: none;' > ".$row['kategoria']." < /div> </div><div class='addtobasket'><i class=\"fas fa-cart-plus\"></i > < /div>";
echo "</section></div>";
}
jQuery:
$("body").on("click", ".addtobasket", function(evt) {
$("#kontener_koszyka").fadeIn();
var suma = 0;
var nazwa = $(".nazwa").text();
var cena = $(".cenaprzedmiotu").text();
var li = "<li class='produkt_w_koszyku'><b>" + nazwa + "</b> <span class='cena_w_koszyku'>" + cena + " zł</span></li>";
$("#koszyk").append(li);
$("#koszyk .cena_w_koszyku").each(function() {
suma += parseFloat($(this).text());
});
$("#cena span").text(suma.toFixed(2));
});
Try this solution:
var nazwa = $(this).closest('.produkt').find('.nazwa').text();
here you are more info about .closest and
.find
Related
Check my image all comment show in one post i am pass post_id 53 56 here is 53 comment and 56 comment you see but it show 53 comment in 56 post i have post and comments system like facebook but my problem is that all comments show in last post. please check it my code i have try many method but it's not working if you have any good solution soo please help me
Controller
public function commentlist(){
$conn = mysqli_connect("localhost","root","","finance");
$memberId = 1;
$sql = "SELECT * FROM tbl_comment INNER JOIN signup ON tbl_comment.u_id = signup.id";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
}
public function commentadd(){
$conn = mysqli_connect("localhost","root","","finance");
$u_id = $this->session->userdata('log_in')['id'];
$u_image = $this->session->userdata('log_in')['image'];
$commentId = isset($_POST['comment_id']) ? $_POST['comment_id'] : "";
$comment = isset($_POST['comment']) ? $_POST['comment'] : "";
$postID = isset($_POST['tmp']) ? $_POST['tmp'] : "";
$name = array();
$name[0] = $this->session->userdata('log_in')['f_name'];
$name[1] = $this->session->userdata('log_in')['l_name'];
$commentSenderName = implode(" ", $name);
$sql = "INSERT INTO tbl_comment(post_id, parent_comment_id,u_id,u_image,comment,comment_sender_name,date) VALUES ('" . $postID . "','" . $commentId . "','" . $u_id . "','" . $u_image . "','" . $comment . "','" . $commentSenderName . "','" . $date . "')";
$result = mysqli_query($conn, $sql);
if (! $result) {
$result = mysqli_error($conn);
}
echo $result;
}
this is my view file
View
<form id="frm-comment_<?php echo $id;?>">
<div class="input-row_<?php echo $id;?>">
<?php if($this->session->userdata('log_in')['image'] !=NULL ): ?>
<img src="<?php echo base_url(); ?>uploads/<?php echo $this->session->userdata('log_in')['image'];?>" style="height:42px; width:42px;" class="img-circle">
<?php else : ?><img src="<?php echo base_url('assets/images/generic-avatar.jpg'); ?>" style="height:42px; width:42px;" class="img-circle">
<?php endif; ?>
<input type="hidden" name="comment_id" id="commentId_<?php echo $id; ?>"/>
<input type="hidden" name="tmp" id="tmp" value="<?php echo $id;?>" />
<input class="input-field" type="text" name="comment" id="comment_<?php echo $id; ?>" placeholder="Write a Comment..">
</div>
<input type="button" class="btn-submit" id="submitButton_<?php echo $id;?>" value="Comment" >
<div id="comment-message_<?php echo $id;?>" style='display: none;'>Comments Added Successfully!</div>
<div class="output_<?php echo $id?>" ></div>
</form>
</div>
</div>
</div>
</div>
Script
<script>
$( "#com_<?php echo $id; ?>" ).click(function() {
$("#comment_<?php echo $id;?>").focus();
});
function postReply(commentId) {
$('#commentId_<?php echo $id; ?>').val(commentId);
$("#comment_<?php echo $id; ?>").focus();
}
$(document).ready(function () {
listComment();
});
$("#submitButton_<?php echo $id;?>").click(function () {
$("#comment-message_<?php echo $id;?>").css('display', 'none');
var str = $("#frm-comment_<?php echo $id;?>").serialize();
$.ajax({
url: "<?php echo base_url();?>finance/commentadd",
data: str,
type: 'post',
success: function (response)
{
var result = eval('(' + response + ')');
if (response)
{
$("#comment-message_<?php echo $id;?>").css('display', 'inline-block');
$("#comment_<?php echo $id; ?>").val("");
$("#commentId_<?php echo $id; ?>").val("");
listComment();
} else
{
alert("Failed to add comments !");
return false;
}
}
});
});
function listComment(){
$.post("<?php echo base_url();?>finance/commentlist",
function (data) {
var data = JSON.parse(data);
var comments = "";
var replies = "";
var item = "";
var parent = -1;
var results = new Array();
var list = $("<ul class='outer-comment'>");
var item = $("<li>").html(comments);
for (var i = 0; (i < data.length); i++)
{
var commentId = data[i]['comment_id'];
var post_id = data[i]['post_id'];
parent = data[i]['parent_comment_id'];
if (parent == "0")
{comments = " \ <div class='comment-row'><div class='comment-info'>\ <img src='<?php echo base_url(); ?>uploads/"+data[i]['image']+"' class='img-circle' style='height:47px; width:47px; border:1px solid white;'>\<div class='comment-text'>\ <span>" + data[i]['post_id'] + "</span><span class='posted-by'>" + data[i]['comment_sender_name'] + "</span> " + data[i]['comment'] + "</div>\
</div>\
<div>\
<a class='btn-reply' style='font-size:14px;' onClick='postReply(" + commentId + ")'> Reply</a>\
<span class='posted-at' style='font-size:12px;'>" + data[i]['date'] + "</span>\
</div>\
</div>";
var item = $("<li>").html(comments);
list.append(item);
var reply_list = $('<ul>');
item.append(reply_list);
listReplies(commentId, data, reply_list);
}
}
$(".output_<?php echo $id?>").html(list);
});
}
function listReplies(commentId, data, list) {
for (var i = 0; (i < data.length); i++)
{
if (commentId == data[i].parent_comment_id)
{
var comments = "\ <div class='comment-row'><div class='comment-info'>\ <img src='<?php echo base_url(); ?>uploads/"+data[i]['image']+"' class='img-circle' style='height:47px; width:47px; border:1px solid white;'>\
<div class='comment-text'> <span class='posted-by'>" + data[i]['comment_sender_name'] + "</span> " + data[i]['comment'] + "</div>\
</div>\
<div>\
\ <span class='posted-at' style='font-size:12px;'>" + data[i]['date'] + "</span>\
</div>\
</div>";
var item = $("<li>").html(comments);
var reply_list = $('<ul>');
list.append(item);
item.append(reply_list);
listReplies(data[i].comment_id, data, reply_list);
}
}
}
</script>
<?php }?>
I think your code is complex because there is not need to save user image ,name in comment table ,you need to use only comment id(auto increment) post id, user id , comment.
Yo get all comments for particular post you should fetch by post ir for that post.
Example :- when user click on particular post , suppose its post id is 1 then as click click on this you have to pass a request with this post id to comment table where query will match this post id in comment id if this condition true then redirect page to view with all comment and show them.
Controller
Query:- $this->model_name->function_name($id);
In model
$this->db->where('post_id', $id);
$this->db->get('comment_table')->result_array();
This query will fetch all comment for clicked post.
i am creating an e-commerce website. if i click a category on the checkbox relevant product should display.but result displayed undefined. what i tried so far i wrote it below.example if select the category as Tv on checkbox. tv product should display. i having a problem on jquery. can you check the jquery if i write correct or not checkbox click part.
Form Design
Category
<div align="left" >
<li class="list-group-item list-group-item-action active" ><h4>Categories</h4></li>
<li id="displayResults" class="list-group-item list-group-item-action">
</li>
</div>
JQuery
function getCategory(){
$.ajax({
type: 'GET',
url: 'get_category.php' ,
dataType: 'JSON',
success: function (data)
{
for (var i = 0; i < data.length; i++)
{
var catname = data[i].catname;
var catid = data[i].id;
var catstatus = data[i].status;
if(catstatus){
$('#displayResults').append('<li id='+catid+' class="list-group-item list-group-item-action"><input id="cat_id'+ catid +'" type="checkbox" value="true" > '+ ' ' + ' <b>'+ data[i].catname + '<b></li>');
}else{
$('#displayResults').append('<li id='+catid+' class="list-group-item list-group-item-action"><b>'+ data[i].catname + '<b><input id="cat_'+ catid +'" type="checkbox" ></li>');
}
}
},
error: function (xhr, status, error)
{
console.log(xhr.message)
}
});
}
Checkbox click
$(document).ready(function() {
$('#displayResults').click(function(){
var cat = $('#cat_id').attr('checked');
alert(cat);
$.ajax({
url: 'get_product.php',
type: 'POST',
data: {cat: cat},
success: function(data){
var len = data.length;
console.log(data);
$("#Products").empty();
for (var i = 0; i < data.length; i++) {
var price = data[i].price;
var image = data[i].image;
var description = data[i].description;
$("#Products").append("<div class='col-md-4'> " +
"<div class='panel panel-info' id='Products'>" +
"<div class='card-body'>" +
"<div class='panel-heading'>" + "<h4> " + description + "</h4> " +
"<p class='panel-body'>" + "<h3> " + price + "</h3>" +
"<p class='panel-body'> <img class='card-img-top' style='width:250px' height='250px' id='theImg' src='images/" + image + "' /> </p>" +
" <a href='#' class='btn btn-primary'>View More</a> </div> </div></div> </div>");
}
}
});
});
});
get_product.php
<?php
include("db.php");
$stmt = $conn->prepare("select id,cat_id,brand_id,price,description,image,keywords from products where cat_id = ? order by RAND() LIMIT 0,6");
$stmt->bind_result($id,$cat_id,$brand_id,$price,$description,$image,$keywords);
$cid = $_POST["cat"];
$stmt->bind_param("s", $cid);
$stmt->bind_result($id,$cat_id,$brand_id,$price,$description,$image,$keywords);
if ($stmt->execute()) {
while ( $stmt->fetch() ) {
$output[] = array ("id"=>$id, "cat_id"=>$cat_id,"brand_id"=>$brand_id,"price"=>$price,"description"=>$description,"image"=>$image,"keywords"=>$keywords);
}
echo json_encode($output);
}
$stmt->close();
?>
$("#cat_id") is wrongly used. There are many category your category id is defined as id="cat_id'+ catid +'".
I am assuming you need to check on single checkbox. if so then it will be better if you use input type radio.
But as you have use checkbox then you can do like this
$(":checkbox").each(function(){
if($(this).is(':checked')){
cat=$(this).val();
alert(cat);
}
});
if you want to select multiple checkbox make cat as array and then pass it to data field.
Hello I Am Working On A Startup and I Have A Huge Problem In My Project.
In Searching Page User Can Search By Different Item And Ads Showed.
I Wanna Per Each Ad In The Picture Area Shows Picture By Slider.
Let Me Show By Pic .
This Is Searching Page
Searchin_Page
I Wanna Use Slider For Each Ad That Shows But Its Dose not Work True . . .
This Is My Jquery Code
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function currentDiv(n) {
showDivs(slideIndex = n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("demo");
if (n > x.length) {
slideIndex = 1
}
if (n < 1) {
slideIndex = x.length
}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" w3-white", "");
}
x[slideIndex - 1].style.display = "block";
dots[slideIndex - 1].className += " w3-white";
}
And This Is Html Side . . .
<div class="Image_Area_Panel">
<div class="w3-content w3-display-container" style="max-width:800px">
<img class="mySlides" src="http://localhost/Ajency/Public/456d6ef5aae4e33926a4c592aa5210a5--sexy-men-hot-men.jpg">
<img class="mySlides" src="http://localhost/Ajency/Public/620b1b643b4d40bef759a386764fc630.jpg">
<img class="mySlides" src="http://localhost/Ajency/Public/Brant-daugherty-cuff.jpg">
<div class="w3-center w3-container w3-section w3-large w3-text-white w3-display-bottommiddle Aroos" style="width:100%">
<div class="AreaBox">
<div class="w3-left w3-hover-text-khaki" onclick="plusDivs(-1)">❮</div>
<div class="w3-right w3-hover-text-khaki" onclick="plusDivs(1)">❯</div>
</div>
<span class="w3-badge demo w3-border w3-transparent w3-hover-white" onclick="currentDiv(1)"></span>
<span class="w3-badge demo w3-border w3-transparent w3-hover-white" onclick="currentDiv(2)"></span>
<span class="w3-badge demo w3-border w3-transparent w3-hover-white" onclick="currentDiv(3)"></span>
</div>
</div>
Sorry For My English Ability
So right now, I am running some PHP code to turn images from a Wordpress post into a slider element.
<?php
$ticker = 0;
$attachments= get_attached_media( 'image', $post->ID );
foreach($attachments as $att_id => $attachment) {
$full_img_url[$ticker] = wp_get_attachment_url($attachment->ID);
?>
<img class="mySlides" src="<?php echo $full_img_url[$ticker]; ?>" >
<?php
$ticker ++;
}
?>
<button class="w3-button w3-display-left" onclick="plusDivs(-1)">❮ </button>
<button class="w3-button w3-display-right"onclick="plusDivs(+1)">❯ </button>
<script>
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("mySlides");
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length} ;
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
}
</script>
My problem appears when I remove an image from the post.
The WordPress post
The slider element that should be there.
The one that shoulds be
So when I remove an image from the post it isn't removed from the slider elements.
I have a system in php, ajax and jquery. This system will search the database queries per page 5 and divide the results into several pages. The problem is that the more the results are more pages are displayed. In the current code, paging is like this: first 1 2 3 4 5 6 last. I would like to remain so: first 1 2 ... 5 6 last. Ie I want to limit the pagination. If I do not limit the pagination when they have more results would look like this: 1234567891011 ...
The code:
<script type="text/javascript">
$(document).ready(function(){
function showLoader(){
$('.search-background').fadeIn(200);
}
function hideLoader(){
$('.search-background').fadeOut(200);
};
$(".pagcon li").click(function(){
showLoader();
$(".pagcon li").removeClass('current');
$(this).addClass("current");
$("#resultado").load("data.php?page=" + this.id, hideLoader)
return false;
});
$("#1").addClass("current");
showLoader();
$("#resultado").load("data.php?page=1", hideLoader);
});
</script>
<style type="text/css">
#consultas {
width:780px;
min-height:245px;
overflow:hidden;
}
.search-background {
background:#FFF;
display:none;
height:154px;
position:absolute;
padding-top:84px;
text-align:center;
opacity:0.5;
filter:alpha(opacity=50);
width:780px;
z-index:999;
}
</style>
<div id="consultas">
<?php
$per_page = 5;
$sql = "select * from consultas ";
$rsd = mysql_query($sql);
$count = mysql_num_rows($rsd);
$pages = ceil($count/$per_page);
?>
<div class="search-background">
<label><img title="Carregando..." src="loader.gif" alt="" /></label>
</div>
<div id="resultado">
</div>
</div>
<ul class="pagination clearfix pagcon">
<?php
//Show page links
echo '<li id="1"><a title="Página 1" href="#">Primeiro</a></li>';
for($i=1; $i<=$pages; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
echo '<li id="'.$pages.'"><a title="Página '.$pages.'" href="#">Último</a></li>';
?>
</ul>
data.php:
<?php
include_once("config.php"); //MYSQL CONFIG
$per_page = 5;
$sqlc = "show columns from consultas";
$rsdc = mysql_query($sqlc);
$cols = mysql_num_rows($rsdc);
$page = $_REQUEST['page'];
$start = ($page-1)*5;
$sql = "select * from consultas ORDER BY data DESC LIMIT $start,5";
$rsd = mysql_query($sql);
?>
<?php
while ($rows = mysql_fetch_assoc($rsd))
{?>
<div class="message status success">
<span><b><?php echo $rows['consulta']; ?> (<font color="#8D4B19"><?php echo $rows['codigo']; ?></font>)</b></span>
<span><?php if(strlen($rows['user']) >= 30){ echo substr($rows['user'], 0, 30)."..."; } else { echo $rows['user']; } ?></span>
<span><b><?php echo $rows['operacao']; ?></b></span>
<span><?php echo date("d/m/Y", strtotime($rows['data'])); ?></span>
<span>R$ <?php echo $rows['valor']; ?></span>
</div>
<?php
}?>
<script type="text/javascript">
$(document).ready(function(){
var Timer = '';
var selecter = 0;
var Main =0;
bring(selecter);
});
function bring ( selecter )
{
$('div.status:eq(' + selecter + ')').stop().animate({ opacity: '1.0', height: '34px' },300,function(){
if(selecter < 6)
{
$('div.status').stop().animate({ opacity: '1.0', height: '17px' },300);
clearTimeout(Timer);
}
});
selecter++;
var Func = function(){ bring(selecter); };
Timer = setTimeout(Func, 20);
}
</script>
Try
$threshold=1;
for($i=1; $i<=$threshold+1; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
echo " ... ";
for($i=$pages-$threshold; $i<=$pages; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
By varying $threshold you can vary the number of page links available.
However, it would be better to present the results as first ... 3 4 5 ... last instead if the user is on the fourth page. This way they can easily move between adjacent pages. Also you can run through the loop fewer times. $current_page is the current page you are on. This needs to be made available to the pagination code somehow.
$threshold=1;
$lower_limit=(($current_page-$threshold)>1)?$current_page-$threshold:1;
$upper_limit=(($current_page+$threshold)<$pages)?$current_page-$threshold:$pages;
for($i=$lower_limit; $i<=$upper_limit; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
Edit for the sake of this specific question
Your pagination is once and not reloaded in the ajax. In order to achieve this reduced pagination, you either need to
load only a few link elements as in either of the choices above and add new link elements or
load all the link elements but hide unnecessary links until they are required.
For the latter:
php
$threshold=1;
for($i=1; $i<=$threshold+1; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
echo " ... ";
for($i; $i<=$pages; $i++)
{
echo '<li id="'.$i.'"'.($i<($pages-$threshold)?'style="display:none"':'')'>'.$i.'</li>';
}
javascript
$(".pagcon li").click(function(){
showLoader();
$(".pagcon li").hide();//hide all links
$(".pagcon li").removeClass('current');
$(this).addClass("current").show();
var id=parse_int($(this).attr(id));
$(".pagcon li:first, .pagcon li:first, .pagcon li#"+(id-1)+" .pagcon li#"+(id+1)).show();//show adjacent links and 'First' and 'Last'
$("#resultado").load("data.php?page=" + this.id, hideLoader)
return false;
});