Post data from one form in a while loop - javascript

I'm trying to post data from a single form in my PHP inside a while loop to another page using jQuery load. Currently when I view the output, only the first result gets to be submitted. When I click on the rest of the forms it keeps refreshing the page. How can I make all the forms to post unique data from my PHP page?
Here is my PHP script:
while (mysqli_stmt_fetch($select_product)): ?>
<div class="col-md-4 top_brand_left" style="margin-top:40px;">
<div class="hover14 column">
<div class="tm_top_brand_left_grid">
<div class="tm_top_brand_left_grid_pos">
</div>
<div class="tm_top_brand_left_grid1">
<figure>
<div class="snipcart-item block">
<div class="snipcart-thumb">
<img class="lazy" title="" alt="" src="/web/images/spinner.gif" data-original="/web/images/<?php echo $product_image; ?>">
<p><?php echo htmlentities($product_name); ?></p>
<h4><?php echo "₦".$product_price; ?><span></span></h4>
</div>
<div class="snipcart-details top_brand_home_details">
<form id="addToCart" method="post">
<fieldset>
<input type="hidden" name="id" id="id" value="<?php echo htmlentities($product_id); ?>">
<input type="submit" id="add_to_cart" name="add_to_cart" value="Add to cart" class="button">
</fieldset>
</form>
</div>
</div>
</figure>
</div>
</div>
</div>
</div>
<?php endwhile; ?>
Here is my jQuery script:
$("#addToCart").submit(function(event){
event.preventDefault();
var page = $("#page").val();
var id = $("#id").val();
var cat_id = $("#cat_id").val();
var res_name = $("#res_name").val();
var add_to_cart = $("#add_to_cart").val();
$("#feedback").load("/web/cart.php", {
page:page,
id: id,
cat_id: cat_id,
res_name: res_name,
add_to_cart: add_to_cart
});
});

Change all your ids for classes in your PHP loop.
Then on click, look for the closest .column to find the relevant element.
$(".addToCart").submit(function(event){
event.preventDefault();
var column = $(this).closest(".column");
var page = column.find(".page").val();
var id = column.find(".id").val();
var cat_id = column.find(".cat_id").val();
var res_name = column.find(".res_name").val();
var add_to_cart = $(this).val();
$("#feedback").load("/web/cart.php", { // This element is outside the PHP loop and has a unique id.
page:page,
id: id,
cat_id: cat_id,
res_name: res_name,
add_to_cart: add_to_cart
});
});

Related

Loop through <li> using javascript/jquery

Note: This is a mixture of Php, Javascript and html.
I have a code below
<div class="chat-sidebar-list-wrapper pt-2">
<h6 class="px-2 pt-2 pb-25 mb-0">MAIDS</h6>
<ul class="chat-sidebar-list maid-list-wrapper">
<?php
foreach($all_maids as $all_maid){
?>
<!-- displaying looped results in <li> using php foreach method-->
<li id="<?php echo $all_maid->id?>" class="bingo">
<input type="hidden" id="hidden_receiver_id" name="hidden_receiver_id" value="<?php echo $all_maid->id?>"/>
<div class="d-flex align-items-center">
<div class="avatar m-0 mr-50"><img src="<?php echo base_url('uploads/'); ?>images/<?php echo get_user_image($all_maid->id)?>" height="36" width="36" alt="sidebar user image">
<span class="avatar-status-busy"></span>
</div>
<div class="chat-sidebar-name">
<h6 class="mb-0 maid-names"><?php echo $all_maid->first_name. "" . $all_maid->last_name ?></h6><span class="text-muted">Maid</span>
</div>
</div>
</li>
<?php } ?>
</ul>
.......
</div>
What i want is, when you click on each <li> items, you should be able to get the ID from the input tag <input type="hidden" id="hidden_receiver_id" name="hidden_receiver_id" value="<?php echo $all_maid->id?>"/>.
So how can i loop the <li> items and get each of it IDs from the input tag?
I tried something below but not working
var listItems = $(".maid-list-wrapper li");
listItems.each(function(idx, li) {
//var id = $(li).text();
alert($("li.bingo").find("input#hidden_receiver_id").text());
});
Using jQuery
var items = $(".chat-sidebar-list li");
items.each(function(id, li) {
var OneItem = $(li);
// and the rest of your code.OneItem is an object here
});
The answer is
i added class="hidden_receiver_id" to <input type="hidden" id="hidden_receiver_id" class="hidden_receiver_id" name="hidden_receiver_id" value="<?php echo $all_maid->id?>"/>
$('.maid-list-wrapper li').click(function() {
//name of each user
console.log($(this).find("h6.maid-names").text());
//ID of each user
//alert($(this).find("input[type='hidden']").val());
console.log($(this).find("input.hidden_receiver_id").val())
});

Unset a single item form a php array embedded in a html site with JS button

My question is. I want to press that remove button at the end and remove my item form the session.
how can i do this?
js:
$('.remove button') .click (function() {
removeItem(This);
});
PHP and HTML:
<?php
foreach($_SESSION["cart"] as $item) {
$data = getProducts($pdo, $item);
if ($data["ColorName"] == NULL) {
$color = "";
} else {
$color = "Color: ".$data["ColorName"]."<br>";
}
if ($data["Size"] == "") {
$size = "";
} else {
$size = "Size: ".$data["Size"]."<br>";
}
print("<div class=\"basket-product\">
<div class=\"item\">
<div class=\"product-image\">
<img src=\"http://placehold.it/120x166\" alt=\"Placholder Image 2\" class=\"product-frame\">
</div>
<div class=\"product-details\">
<h1><strong><span class=\"item-quantity\">1</span> x ".$data["StockItemName"]."</strong></h1>
<p><strong>".$color." ".$size."</strong></p>
<p>Product Code - ".$data["StockItemID"]."</p>
</div>
</div>
<div class=\"price\">".$data["RecommendedRetailPrice"]."</div>
<div class=\"quantity\">
<input type=\"number\" value=\"1\" min=\"1\" class=\"quantity-field\">
</div>
<div class=\"subtotal\">". $data["RecommendedRetailPrice"] * 1 ."</div>
<div class=\"remove\">
<button>Remove</button>
</div>
</div>");
}
I tried using Unset in allot of places, but that doesn't seem to get working :')
:)
The solution is rather easy, but requires some explanation in order to be understood.
What you need here is to:
Create a new php file, which would fetch the post data (in this case ID of an element) and then simply unset the key (sub-array), which contains the cart item you want to remove.
You can use $key_to_remove = array_search($_POST['stock_item_id'], array_column($_SESSION["cart"], 'StockItemID')); and then simply unset it unset($_SESSION["cart"][$key_to_remove]);
Assign id="remove_<?php echo $data["StockItemID"]; ?>" to the <div class="basket-product"> and data-product-id="<?php echo $data["StockItemID"]; ?>" to the button, so you can identify it for item removal via javascript/jquery and you need that value extracted later for the item you want to remove from the corresponding session array (which is, in this case, $_SESSION["cart"]).
Create a callback function for removal on('click', function(){});
Inside that function extract that value data-product-id from the button you just clicked var stock_item_id=$(this).attr('data-product-id');
Inside the same function, after step 4, create an ajax call to the file from step 1 with the post data from step 4
On successful execution of an ajax call, delete the corresponding product row you have marked with id="remove_<?php echo $data["StockItemID"]; ?>" in step 2 with the following code $("#remove_"+stock_item_id).remove();
In the end, your code would look like this
YOUR INITIAL PHP AND HTML (With small corrections)
<?php
foreach($_SESSION["cart"] as $item) {
$data = getProducts($pdo, $item);
if ($data["ColorName"] == NULL) {
$color = "";
} else {
$color = "Color: ".$data["ColorName"]."<br>";
}
if ($data["Size"] == "") {
$size = "";
} else {
$size = "Size: ".$data["Size"]."<br>";
}
?>
<div class="basket-product">
<div class="item">
<div class="product-image">
<img src="http://placehold.it/120x166" alt="Placholder Image 2" class="product-frame">
</div>
<div class="product-details">
<h1>
<strong>
<span class="item-quantity">
1
</span>
x <?php echo $data["StockItemName"]; ?>
</strong>
</h1>
<p>
<strong>
<?php echo $color." ".$size; ?>
</strong>
</p>
<p>
Product Code - <?php echo $data["StockItemID"]; ?>
</p>
</div>
</div>
<div class="price">
<?php echo $data["RecommendedRetailPrice"]; ?>
</div>
<div class="quantity">
<input type="number" value="1" min="1" class="quantity-field">
</div>
<div class="subtotal">
<?php echo $data["RecommendedRetailPrice"]; ?> * 1
</div>
<div class="remove">
<button data-product-id="<?php echo $data["StockItemID"]; ?>">
Remove
</button>
</div>
</div>
<?php
}
?>
JS
$(document).ready(function(){
$('.remove button').on('click', function() {
var stock_item_id=$(this).attr('data-product-id');
$.ajax({
url: "new_php_file_created_to_remove_item_from_session_via_ajax.php",
data:
{stock_item_id : stock_item_id}
}).done(function() {
$("#remove_"+stock_item_id).remove();
});
});
});
NEW PHP FILE (new_php_file_created_to_remove_item_from_session_via_ajax.php)
<?php
$stock_item_id = $_POST['stock_item_id'];
$key_to_remove = array_search($_POST['stock_item_id'], array_column($_SESSION["cart"], 'StockItemID'));
unset($_SESSION["cart"][$key_to_remove]);
if(isset($_SESSION["cart"][$key_to_remove])) {
return false;
}
return true;
For the sake of readability and further maintenance and possible additions, I would strongly recommend you to separate php, html and js code into separate files, but that's only a suggestion. :)

select specific element jquery inside php foreach loop

I have foreach loop in php on front page for getting images and description of the image, inside foreach loop I have form, form is use for sending comment, this is front page..
<?php foreach ($photo as $p) : ?>
<div class="photo-box">
<div class="galP photo-wrapper" >
<div data-fungal="<?php echo $p->id; ?>" class='galFun-get_photo'>
<img src="<?php echo $p->thumb; ?>" class='image'>
</div>
</div>
<div class='inline-desc'>
<a href="/gallery/user.php?id=<?php echo $p->userId; ?>">
<?php echo $p->username; ?>
</a>
</div>
<form method="POST" action="" class="form-inline comment-form galForm">
<div class="form-inline">
<input type="hidden" class='photoId form-control' name="photoId" value="<?php echo $p->id; ?>" >
<input type="hidden" class='userId form-control' name="userId" value="<?php echo $session->userId; ?>" >
<textarea cols="30" rows="3" class='comment fun-gal-textarea' name="comment" placeholder="Leave your comment"></textarea>
<button type='button' name='send' class='sendComment'>SEND</button>
</div>
</form>
<div class='new-comm'></div>
<div class='comments-gal' id='comments'>
<div data-id='<?php echo $p->id; ?>' class='getComment'>
<span>View comments</span>
</div>
</div>
</div>
Using ajax I want to send userId,photoId and comment after clicking the button that has class sendComment. When I send comment on the first image everything is ok but when I try to send comment for some other image it wont work. I can't select that specific input and textarea for geting the right value .This is my jquery
$('body').on('click','.sendComment',function(){
var selector = $(this);
var userId = selector.siblings($('.userId'));
var photoId = selector.siblings($('.photoId'));
var c = selector.siblings($('.comment'));
var comment = $.trim(c.val());
if (comment == "" || comment.length === 0) {
return false;
};
$('#no-comments').remove();
$.ajax({
url: '/testComment.php',
type: 'POST',
data: {comment:comment,userId:userId,photoId:photoId}
}).done(function(result) {
...
}
})
});
Also, I have tried in every possible way to get the right value from the form without success..
This line
var userId = selector.siblings($('.userId'));
will be unlikely to get the correct input as, according to https://api.jquery.com/siblings/
.siblings( [selector ] )
selector
A string containing a selector expression to match elements against.
so this would need to be :
var userId = selector.siblings('.userId');
at that point you also need to get the actual value from the input, giving:
var userId = selector.siblings('.userId').val();
var photoId = selector.siblings('.photoId').val();
var c = selector.siblings('.comment');
and the rest of the code as-is.

XMLHttpRequest PHP Chats

I am trying to create a system to display messages on 2 or more separate chats( with different messages stored in a db) on the same page. The chats each have ids to differentiate them and I have created a function to go through each chat in use and print the approprite messages for them but only 1 chat gets the messages.
The Code:
The HTML
<div class="full_wrap">
<div class="force-overflow"></div>
<div id="Sidenav" class="side">
<h2>Chat Settings & Info</h2>
<a id="closebtn" href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<div class="authr">
<a>
<div class="authr_img"></div>​
</a>
<form action="mypage.php" method="post">
<div class="authr_name">
<button value="<?php echo $chat_authr ?>" name="userlink" class="subm_as_text"><?php echo $chat_authr; ?></button>
</div>
</form>
</div>
<div class="chat_info">
<div class="chat_descy">
<h2>Chat Description</h2>
<div class="descc">
<h3><?php echo $chat_description; ?></h3>
</div>
</div>
<div class="chat_fol"><h2>Chat users: <?php echo $num_users; ?></h2></div>
<div class="chat_back">
<h2> Change Chat Wallpaper</h2>
<form method="post" action="picture.php" enctype="multipart/form-data">
<input type="file" id="upload" class="custom-file-input" name="chat_wall">
<input type="submit" class="chat_wall_subm" value="Change"/>
</form>
</div>
</div>
<form method="post" action="chat.php" >
<!--<input type="submit" class="chat_leave" name="" value="Leave Chat">-->
<button class="chat_leave" name="chat_leave" value="<?php echo $chat_index; ?>" >Leave Chat</button>
</form>
</div>
<div class="mnav">
<span onclick="openNav()">☰</span>
<i class="material-icons" id="chat_un_small" onclick="chat_un_small()">arrow_upward</i>
<h1><?php echo $chat_title ?></h1>
</div>
<!--one ting-->
<div class="conceal_wrapper">
<div class="msgs" id="5e2dbe2be3b5927c588509edb1c46f7d">
</div>
<form method="post" id="form_5e2dbe2be3b5927c588509edb1c46f7d" class="comform">
<div class="wcom" >
<input maxlength="140" type = "text" id="5e2dbe2be3b5927c588509edb1c46f7d" class="comin" placeholder="My message..." name="sendmsg" autocapitalize="off" autocorrect="off"/>
<input class="hidden_index" type="text" value="5e2dbe2be3b5927c588509edb1c46f7d" name="chat_index"/>
</div>
</form>
</div>
<div class="chat_enlarge">
<div class="chat_enlarge_full" onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_full()"></div>
<div class="chat_enlarge_standard" onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_standard()"></div>
<div class="chat_enlarge_small" onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_small()"></div>
</div>
</div>
<div class="full_wrap">
<div class="force-overflow"></div>
<div id="Sidenav" class="side">
<h2>Chat Settings & Info</h2>
<a id="closebtn" href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<div class="authr">
<a>
<div class="authr_img"></div>​
</a>
<form action="mypage.php" method="post">
<div class="authr_name">
<button value="<?php echo $chat_authr ?>" name="userlink" class="subm_as_text"><?php echo $chat_authr; ?></button>
</div>
</form>
</div>
<div class="chat_info">
<div class="chat_descy">
<h2>Chat Description</h2>
<div class="descc">
<h3><?php echo $chat_description; ?></h3>
</div>
</div>
<div class="chat_fol"><h2>Chat users: <?php echo $num_users; ?></h2></div>
<div class="chat_back">
<h2> Change Chat Wallpaper</h2>
<form method="post" action="picture.php" enctype="multipart/form-data">
<input type="file" id="upload" class="custom-file-input" name="chat_wall">
<input type="submit" class="chat_wall_subm" value="Change"/>
</form>
</div>
</div>
<form method="post" action="chat.php" >
<!--<input type="submit" class="chat_leave" name="" value="Leave Chat">-->
<button class="chat_leave" name="chat_leave" value="<?php echo $chat_index; ?>" >Leave Chat</button>
</form>
</div>
<div class="mnav">
<span onclick="openNav()">☰</span>
<i class="material-icons" id="chat_un_small" onclick="chat_un_small()">arrow_upward</i>
<h1><?php echo $chat_title ?></h1>
</div>
<!--one ting-->
<div class="conceal_wrapper">
<div class="msgs" id="9503e253936e716f18d9c57b4f97d618">
</div>
<form method="post" id="form_9503e253936e716f18d9c57b4f97d618" class="comform">
<div class="wcom" >
<input maxlength="140" type = "text" id="9503e253936e716f18d9c57b4f97d618" class="comin" placeholder="My message..." name="sendmsg" autocapitalize="off" autocorrect="off"/>
<input class="hidden_index" type="text" value="9503e253936e716f18d9c57b4f97d618" name="chat_index"/>
</div>
</form>
</div>
<div class="chat_enlarge">
<div class="chat_enlarge_full" onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_full()"></div>
<div class="chat_enlarge_standard" onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_standard()"></div>
<div class="chat_enlarge_small" onmouseover="chat_action(this)" onmouseout="chat_action_negative(this)" onclick="chat_enlarge_small()"></div>
</div>
</div>
So there are 2 chats separated by the full_wrap class. The msgs have different id for the chat index stored unique for each chat in the db
The Javascript:
$( document ).ready(function() {
chat_receivemsgs();
});
function chat_receivemsgs(){
var cusid_ele = document.getElementsByClassName('msgs');
if(cusid_ele.length == 0) {
console.log("hi");
} else {
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var item_id = item.id;
console.log(cusid_ele.length);
for (var i = 0; i < cusid_ele.length; ++i) {
var item = cusid_ele[i];
var item_id = item.id;
console.log(item_id);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("yes");
console.log(item_id);
// document.getElementById(item_id).innerHTML = this.responseText;
$("#"+item_id).html(this.responseText);
}else{
console.log("no");
console.log(item_id);
}
}
xmlhttp.open("GET","receivemsg.php?q="+item_id,true);
xmlhttp.send();
}
}
}
}
receivemsgs.php just selects all messages in the messages table with the index of the index given by item_id. The problem is as stated that only the chat with 9503e253936e716f18d9c57b4f97d618 id receives the messages.
I heard that the requests repeat 4 times but I am not an expert in this field. By using the console, I understood that it ignores the first chat and only generates the messages for 9503e253936e716f18d9c57b4f97d618.
Any help would appreciate.
Also if there is a better way to control more than one chat on the same page, I wold love to know how to.
Thank you for your time.
The problem lies in how you're using XMLHttpRequest.
See this snippet:
function Obj() {
}
Obj.prototype = {
callFunc: function() {
setTimeout(this.func, 1000);
}
};
function test() {
var ids = ['id1', 'id2'];
for (var i = 0 ; i < 2 ; ++i) {
var id = ids[i];
var obj = new Obj();
obj.func = function() {
console.log(id);
};
obj.callFunc();
}
}
test();
As you can see, the code prints "id2" twice to the console. That's similar to your problem.
What happens is that, in obj.func (in your code, that's xmlhttp.onreadystatechange), the id variable (respectively item_id) comes from the outer function. Its value when obj.func is assigned is not "saved". When the function finally gets executed, it will use the last known value for that variable.
So here's what happens:
i = 0
id = ids[0] = 'id1'
a new Obj is created (let's call it obj1) and assigned to obj
obj1.func is created
obj1.callFunc is called, it programs obj1.func to be called later
i = 1
id = ids[1] = 'id2'
a new Obj is created (let's call it obj2) and assigned to obj
obj2.func is created
obj2.callFunc is called, it programs obj2.func to be called later
obj1.func gets called, it prints the last value of id, that is "id2"
obj2.func gets called, it prints the last value of id, that is "id2"
There are a few ways around that behavior. You could retrieve item_id from PHP's output somehow. You could set item_id to a member of xmlhttp and use that in your function (xmlhttp.item_id = item_id; then inside the function this.item_id). Or you could use bind. With the latter solution, your code becomes:
xmlhttp.onreadystatechange = function(this_item_id) {
if (this.readyState == 4 && this.status == 200) {
console.log("yes");
console.log(this_item_id);
// document.getElementById(this_item_id).innerHTML = this.responseText;
$("#"+this_item_id).html(this.responseText);
}else{
console.log("no");
console.log(this_item_id);
}
}.bind(xmlhttp, item_id);
xmlhttp.open("GET","receivemsg.php?q="+item_id,true);
xmlhttp.send();
By the way, I don't understand why you're iterating twice on cusid_ele (you have two nested loops).

I'm trying to get the id when clicking different messages from sql database

I'm trying to get the id when I click different messages.
This is my javascript:
$(document).ready(function() {
$('#message-subject-result').click(function(){
var message = document.getElementById('message_id').value;
alert(message);
});
});
I am pulling it from a php function that is:
<div id="message-subject-result">
<div id="message-date">'.$date.'</div>
<input type="hidden" id="message_id" value="'.$row['mes_id'].'"><div id="message-sender-name">FROM: '.$row['firstname'].' '.$row['lastname'].'</div>
<div id="message-subject">SUBJECT: '.$row['subject'].'</div>
<div id="message-preview">'.$row['message'].'</div>
</div>
The javascript works but only when I click on the first echoed result. What am I doing wrong?
Replace duplicating ids with classnames and use find method:
$('.message-subject-result').click(function() {
var messageId = $(this).find('.message_id').val();
alert(messageId);
});
valid HTML should be:
<div class="message-subject-result">
<div clas="message-date">'.$date.'</div>
<input type="hidden" class="message_id" value="'.$row['mes_id'].'">
<div class="message-sender-name">FROM: '.$row['firstname'].' '.$row['lastname'].'</div>
<div class="message-subject">SUBJECT: '.$row['subject'].'</div>
<div class="message-preview">'.$row['message'].'</div>
</div>
You must have all unique ids. Something like this will give you unique id's:
<?php
$i = 0;
foreach($result as $row) { ?>
<div id="message-subject-result">
<div id="message-date">'.$date.'</div>
<input type="hidden" id="message_id<?php echo $i; ?>" value="'.$row['mes_id'].'"><div id="message-sender-name">FROM: '.$row['firstname'].' '.$row['lastname'].'</div>
<div id="message-subject">SUBJECT: '.$row['subject'].'</div>
<div id="message-preview">'.$row['message'].'</div>
</div>
<?php $i++;
} ?>

Categories

Resources