a foreach loop is produce many element with same class in a div(the div is curectly present with id "#show_case" )
foreach ($messages as $key => $value) { ?>
<div class="message">
<p class="username"><?php echo $value['username']; ?></p> <span>say:</span>
<p class="text"> <?php echo $value['message']; ?></p>
<p class="message_id"><?php echo $value['message_id']?></p>
</div> <?php }
}
i built a right click context menu that have a delete button that have id #delete and do this code when is clicked
$('#delete').click(function(e) {
e.preventDefault();
var id = $('.message_id').text();
$.ajax({
url: 'ajax/chat.php',
type: 'POST',
data: {
method: "delete",
id: id,
},
success: function (data) {
alert('successfully deleted');
}
});
});
delete button is here (it is a right click contextmenu will be avilibe after right click on the element)
<div class="menu">
<ul>
<li>
<button id="delete">delete</button>
</li>
</ul>
</div>
i tryed
var id = $('.message_id').text();
for get id but it return all elements ids by class message_id ... i what just the id of element that clicked by delete button
where is your #delete button?
If the delete button contains .message_id, you can use
var id = $(this).find('.message_id').text();
I have created a DEMO to get the id of the element on right click and save this id into an input or hidden element so that the can be retrieved in different functions. Here is the code from the DEMO:
HTML:
<h3>Right click on below messages</h3>
<div class="message" style="border:1px dotted">
<p class="username">Username 1</p> <span>say:</span>
<p class="text"> text 1</p>
<p class="message_id">1</p>
</div>
<br>
<div class="message" style="border:1px dotted">
<p class="username">Username 2</p> <span>say:</span>
<p class="text"> text 2</p>
<p class="message_id">2</p>
</div>
<br>
Selected message id:
<input type="text" id="selected_message_id" />
JS:
$(function () {
$(".message").contextmenu(function() {
alert("clicked message id = "+$(this).find('.message_id').html());
$('#selected_message_id').val($(this).find('.message_id').html());
return false;
});
});
Now in your below function, you can get the message_id like this:
$('#delete').click(function(e) {
e.preventDefault();
var id = $('#selected_message_id').val();//get the message_id from the hidden/text input
$.ajax({
url: 'ajax/chat.php',
type: 'POST',
data: {
method: "delete",
id: id,
},
success: function (data) {
alert('successfully deleted');
}
});
});
Related
I am currently studying programming and trying to build a website with .Net Core.
I have the following issue. I am not familiar with JavaScript that much and I have two JQuery/AJAX functions on my Index page. One of the function is for the posts likes/dislikes and the other for posts comments.
My ViewModel contains a collection of Posts:
public IEnumerable<IndexPostViewModel> Posts { get; set; }
public int PagesCount { get; set; }
public int CurrentPage { get; set; }
Into my view I am looping through each Post and in it, through each Comment.
#foreach (var post in Model.Posts)
{
<div class="post-content">
<img src=#post.ImageUrl width="500" height="500" alt="post-image" class="img-responsive post-image" />
<div class="post-container">
<img src="http://placehold.it/300x300" alt="user" class="profile-photo-md pull-left" />
<div class="post-detail">
<div class="user-info">
<h5>#post.User.UserName <span class="following">following</span></h5>
<p class="text-muted">Post published at: #post.CreatedOn</p>
</div>
<div class="reaction">
<a class="btn text-green" href="#" method="post" onclick="sendVote(#post.Id, true)"><div class="icon ion-thumbsup" id="upVotes">#post.UpVotes</div></a>
<a class="btn text-red" href="#" method="post" onclick="sendVote(#post.Id, false)"><div class="fa fa-thumbs-down" id="downVotes">#post.DownVotes</div></a>
</div>
<div class="line-divider"></div>
<div class="post-text">
<p>#post.Text</p>
</div>
<div class="line-divider"></div>
#foreach (var comment in post.Comments)
{
<div class="post-comment">
<img src="http://placehold.it/300x300" alt="" class="profile-photo-sm" />
<p>#post.User.Email<i></i> #comment.Text</p>
</div>
}
<form id="myForm" asp-controller="Comment" asp-action="Create" method="post">
<input type="hidden" name="PostId" id="postId" value="#post.Id" />
<textarea name="text"></textarea>
<input type="submit" value="Submit Comment" />
</form>
</div>
</div>
</div>
And these are the functions in the Scripts section:
#section Scripts {
function sendVote(postId, isUpVote) {
var json = { postId: postId, isUpVote: isUpVote };
$.ajax({
url: "/api/votes",
type: "POST",
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#upVotes").html(data.upVotes);
$("#downVotes").html(data.downVotes);
}
});
}
// wait for the DOM to be loaded
$(document).ready(function () {
// bind 'myForm' and provide a simple callback function
$('#myForm').each.ajaxForm(function () {
alert("You have just posted a comment");
document.location.reload(true);
});
});
</script>
}
My issue is that both functions are working correctly only for the first post. Can you please assist on how to modify the functions to be applied for each element in the loop?
Thanks in advance.
the problem is simple.
your selector and ids are not unique
id can only be defined for one element, same id on multiple/same elements will cause this issue.
the link tag has a common id for all records, it needs to be unique.
make the ids unique , i added #post.Id with ids, this will make each unique
<div class="reaction">
<a class="btn text-green" href="#" method="post" onclick="sendVote(#post.Id, true)"><div class="icon ion-thumbsup" id="upVotes_#post.Id">#post.UpVotes</div></a>
<a class="btn text-red" href="#" method="post" onclick="sendVote(#post.Id, false)"><div class="fa fa-thumbs-down" id="downVotes_#post.Id">#post.DownVotes</div></a>
</div>
and in you js change the selector by adding id
function sendVote(postId, isUpVote) {
var json = { postId: postId, isUpVote: isUpVote };
$.ajax({
url: "/api/votes",
type: "POST",
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#upVotes_"+postId).html(data.upVotes); // change here
$("#downVotes_"+postId).html(data.downVotes);
}
});
}
and also for myform do the same, you dont need id for form, but if you want just add the #post.Id to id,
<form id="myForm" class="myform" asp-controller="Comment" asp-action="Create" method="post">
<input type="hidden" name="PostId" id="postId" value="#post.Id" />
<textarea name="text"></textarea>
<input type="submit" value="Submit Comment" />
</form>
and in event change id to class to make it dynamic,
$('.myForm').each.ajaxForm(function () {
// $(this) will give you access to the specific form only
alert("You have just posted a comment");
document.location.reload(true);
});
I am trying to catch an integer id with "onClick" function. And send it database with ajax. And display all related information to this id in alert box.
<button class="show">Show Popup</button>
<div class="Popup Confirm">
<input type="text" id="id" />
<button type="button" onclick="getId(document.getElementById('id').innerHTML);">Get</button>
</div>
<script>
$('.show').click(function(){
$(".Popup").show();
$("#id").val(4);
});
function getId(id = null) {
if(id) {
$.ajax({
url: 'abc.php',
type: 'post',
data: {id: id},
dataType: 'text',
success:function(response) {
alert(id);
}
});
}
else {
// error messages
alert("No id selected");
}
}
</script>
Instead of
<button type="button" onclick="getId(document.getElementById('id').innerHTML);">Get</button>
you should use:
<button type="button" onclick="getId(document.getElementById('id').value);">Get</button>
The input field value is available through the value property, not innerHTML.
Fiddle: https://jsfiddle.net/3cjh6bf0/
I need someone to help me please to insert multiple products to cart, adding single one is working fine but I have one product which inserting with no issue and related products which have checkboxes where I need to add it but dont know how
enter image description here
ajax for adding product:
<script>
$(function(){
$('.add_to_cart').on("click", function () {
var id = ($("#item_id").val());
$.ajax({
url: 'cart/' + id+'/edit',
type: "get",
success: function (data) {
$('#myModal').modal('hide');
$('#cart_product').html(data);
}
});
});
});
</script>
add in controller
public function edit(Request $request,$id)
{
$quantity=$request->quantity;
$product=Product::find($id);
Cart::add($id,$product->product_title,$quantity,$product->product_price);
$products = Cart::content();
foreach($products as $Product){
echo '<div class="OrderItem_root styles_base styles_spacing-base">
<div class="OrderItem_quantity styles_just-right styles_base styles_spacing-base">'.$Product->qty.'</div>
<div class="OrderItem_container">
<div class="OrderItem_category"></div>
<div class="OrderItem_itemHeader">
<div id="cartprice" class="OrderItem_total">$'.$Product->price*$Product->qty.'</div>
<input id="mycartprice" type="text" name="mycartprice" value="'.$Product->price.'" hidden="">
</div>
<div>
</div>
<div>
<button class="remove_item OrderItem_action Button_root" data-id="'.$Product->rowId.'" data-price="'.$Product->price*$Product->qty.'" data-qty="'.$Product->qty.'" type="submit">Remove</button>
</div>
</div>
</div>';
}
}
related items
foreach($products as $Product){
echo '<div class="SuggestedItem_container">
<label>
<input id="ppleadd" type="checkbox" onchange = "AutoCalculateMandateOnChange(this)">
<span id="related_item" class="SuggestedItem_name">'.$ProductDetails->product_title.'</span><span class="SuggestedItem_price styles_small styles_base styles_spacing-base">+$'.$ProductDetails->product_price.'</span></div></div>
</div>
</label>';
}
to solve this issue use this
<input id="ppleadd" type="checkbox" class="get_value" data-id="'.$ProductDetails->product_id.'" >
$(document).ready(function(){
$('.testbtn').on("click", function (){
var insert=[];
$('.get_value').each(function(){
if($(this).is(":checked"))
{
insert.push($(this).attr('data-id'));
}
});
insert=insert.toString();
$.ajax({
url:"add-to-cart",
method:"get",
data:{insert:insert},
success:function(data){
} }); }); });
I have a small snippet which is a comment system. I am trying to make it so when I press submit, the form itself will refresh and so will the comments.
I have tried using AJAX but I can't see anything actually initiating when I press "Submit".
My frontpage.php includes each element of the player.
and here is the core for the player_comments.php:
<script>
$(document).ready(function() {
var options = {
url: '',
target: '#comment-text', // target element(s) to be updated with server response
type: 'post' // 'get' or 'post', override for form's 'method' attribute
};
// bind form using 'ajaxForm'
$('#song-comment-form').ajaxForm(options);
});
</script>
<?
}
if(isset($userId)) {
/* logged in only */
}
$iComments = 0;
$qComments = $db->query("
SELECT songs_comments.*, user.id AS uId, user.username AS uName, user.avatar AS uAvatar
FROM songs_comments LEFT JOIN user ON songs_comments.userid_from = user.id
WHERE songs_comments.songid = '".$rSong->id."' ORDER BY songs_comments.id DESC");
while ($rComments = $qComments->fetch_object()) {
$showComments .= '
<img src="../'.makeAvatar($rComments->uId,$rComments->uAvatar,50).'" class="avatar float-left" alt>
<div class="comment">
<div class="comment-text">'.$rComments->text.'</div>
<div class="comment-footer">
'.$rComments->uName.' on '.dateStamp($rComments->time).'
</div>
<br style="clear:both;">
</div>
';
$iComments++;
} ?>
<div id="player-song-comments-wrap">
<div id="player-song-comments-heading"><img src="template/images/icons/comments.png" alt> Comments</div>
<div id="player-song-comments-sub-heading">
<?=isset($userId)?'Add comment':'Add comment'?>
<span id="song-comments-num"><?=$iComments?></span> comments for "<span id="song-comments-title"><?=$rSong->title?></span>"
by <span id="song-comments-artist"><?=$rSong->artist?></span>
</div>
<hr>
<form id="song-comment-form">
<input type="hidden" value="<?=$rSong->id?>" class="song-id">
<textarea class="editor" id="song-comment-textarea"></textarea><br>
<input type="submit" value="Submit"><input type="button" value="Cancel" id="hide-song-comment-form">
<hr>
</form>
<div id="player-song-comments">
<?=$showComments?>
</div>
</div>
How do I make it so that when I click submit, everything inside this include is reloaded?
here your ajax call code
<script>
$(document).ready(function(){
$("#submit_data").on('click',function(e){
$.ajax({
type:'POST',
url:"player_comments.php",
success:function(data){
console.log(data);
$("#player-song-comments-wrap").html(data)
}
});
});
});
</script>
<form id="song-comment-form">
<input type="hidden" value="<?php echo $rSong->id ?>" class="song-id">
<textarea class="editor" id="song-comment-textarea"></textarea><br>
<input type="submit" value="Submit" id="submit_data"><input type="button" value="Cancel" id="hide-song-comment-form">
<hr>
</form>
<div id="player-song-comments-wrap">
</div>
here your player_comments.php code which call in ajax url
<?php
if(isset($userId)) {
/* logged in only */
}
$iComments = 0;
$qComments = $db->query("
SELECT songs_comments.*, user.id AS uId, user.username AS uName, user.avatar AS uAvatar
FROM songs_comments LEFT JOIN user ON songs_comments.userid_from = user.id
WHERE songs_comments.songid = '".$rSong->id."' ORDER BY songs_comments.id DESC");
while ($rComments = $qComments->fetch_object()) {
$showComments .= '
<img src="../'.makeAvatar($rComments->uId,$rComments->uAvatar,50).'" class="avatar float-left" alt>
<div class="comment">
<div class="comment-text">'.$rComments->text.'</div>
<div class="comment-footer">
'.$rComments->uName.' on '.dateStamp($rComments->time).'
</div>
<br style="clear:both;">
</div>
';
$iComments++;
}
?>
I am developing shopping cart in codeigniter where I am fetching data from data base and when user clicks on add to cart the the data related to current item which is clicked by user get store in jQuery variables now I am facing problem that onclick event works only on first fetched item and on the rest it won't works and I am confuse why it's not working.
Here is my code.
<div class="col-md-9" >
<?php if(isset($products))
{
foreach($products as $row)
{
?>
<div class="row" >
<div class="col-md-4" id="con">
<div class="product">
<a href="products/<?=$row->sub_c_id?>/<?=$row->pid?>">
<img id="imgslct" alt="<?=$row->pname?>" height="173" width="144" src="<?php echo base_url(); ?>uploads/<?=$row->product_pic?>">
</a>
<div class="name">
<?=$row->pname?>
</div>
<div class="price">
<p id="price">price : <?=$row->pprice?></p>
<input type="hidden" id="pquan" value="<?=$row->pquantity;?>">
<button id="addtocart" class="btn btn-lg btn-default">Add to cart</button>
</div>
</div>
</div>
<?php
}
} ?>
Here is JQuery code.
<script type="text/javascript">
$(document).ready(function() {
var counter=0;
$("#con").on('click',function(){
counter++;
var pic=$(this).find("img").attr('src');
alert(pic);
var imgdata= $(this).find("#pname").text();
var productquantity= $('#pquan').val();
var productid=$('#pid').text();
var price=$("#price").text();
var qty="1";
var session_id="<?=$this->session->userdata('session_id');?>";
var pid="1";
$("#counter").text(counter);
var counting= $("#counter").text(counter);
<?php $counting=''?>+counting;
alert(counting);
<?php $new_data=array('counter' => $counting ) ?>
if(qty=="")
{
alert("no quantity added");
return false;
}
$.ajax({
type:"post",
url:"<?=base_url();?>temp_upload",
data:"pic="+pic+"&imgdata="+imgdata+"&productquantity="+productquantity+"&productid="+productid+"&price="+price+"&qty="+qty+"&session_id="+session_id+"&pid="+pid,
success: function(data)
{
alert(data);
$("#uploaded").html();
}
});
$("#newdata").append('<tr><td class="image"><img alt="IMAGE" class="img-responsive" src="'+pic+'"></td><td class="name">Black Dress</td><td class="quantity">x 3</td><td class="total">'+price+'</td><td class="remove"><img src="'+pic+'" alt="Remove" title="Remove"></td></tr>');
});
});
</script>
IDs should be unique.
The moment you change the id to a class (#con -> .con) and modify your code appropriatelly, they all will be selected.
See this example: http://jsfiddle.net/shomz/38PB2/
You are within a loop that is using the same id over and over with id="con" being the first. Since ids must be unique within the DOM, you need to change them from an id to a class.
You should do something like:
<div class="col-md-4 con">
<div class="product">
<a href="products/<?=$row->sub_c_id?>/<?=$row->pid?>">
<img class="imgslct" alt="<?=$row->pname?>" height="173" width="144" src="<?php echo base_url(); ?>uploads/<?=$row->product_pic?>">
</a>
<div class="name">
<?=$row->pname?>
</div>
<div class="price">
<p>price : <?=$row->pprice?></p>
<input type="hidden" class="pquan" value="<?=$row->pquantity;?>">
<button class="addtocart btn btn-lg btn-default">Add to cart</button>
</div>
</div>
</div>
Then change the beginning of your JavaScript to:
$(".con").on('click', function ()
{
counter++;
var $this = $(this);
var pic = $this.find("img").attr('src');
var imgdata = $this.find(".pname").text();
var productquantity = $this.find('.pquan').val();
var productid = $this.find('.pid').text();
var price = $this.find(".price").text();
var qty = "1";
var session_id = "<?=$this->session->userdata('session_id');?>";
var pid = "1";
first change the event to be attached to class not to id as id must be unique ,if you attach click event to id ,only the first element with that id will trigger that event
change
<div class="col-md-4" id="con">
to
<div class="col-md-4 con" >
also you have link tag inside that div which will make some problems till to stop propagation of that event
then to add click event to fetched elements you can use
$(document).on('click','.con',function(){
/// your code
});
so click event will be attached to the new elements too