select specific element jquery inside php foreach loop - javascript

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.

Related

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. :)

Post data from one form in a while loop

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
});
});

Email input is not taking email address as valid input in newsletter subscribe box

I have newsletter subscribe input in opencart website and when i input email and press subscribe it says "Email is not valid!: even thou it is.
So i cant use it since it doesnt take emails.
I used this theme and didnt change anything in the subscribe module,
you can scroll down to the footer and check how it behaves here: http://demopavothemes.com/pav_woosa/demo2/
Cant figure out what is the problem.
Heres the code of the module:
<div class="<?php echo $prefix; ?> newsletter-v1" id="newsletter_<?php echo $position.$module;?>">
<form id="formNewLestter" method="post" action="<?php echo $action; ?>" class="formNewLestter">
<div class="panel panel-v1">
<div class="panel-heading">
<h4 class="panel-title"><?php echo $objlang->get("entry_newsletter");?></h4>
</div>
<div class="panel-body">
<div class="input-group">
<input type="text" placeholder="Email Here ..." class="form-control email" <?php if(!isset($customer_email)): ?> <?php endif; ?> size="18" name="email">
<div class="input-group-btn pull-left">
<button type="submit" name="submitNewsletter" class="btn btn-primary icon-mail radius-6x"><?php echo $objlang->get("button_subscribe");?></button>
</div>
</div>
<input type="hidden" value="1" name="action">
<div class="valid space-top-10"></div>
</div>
<?php if (!empty($social)): ?>
<?php echo html_entity_decode( $social );?>
<?php endif ?>
</div>
</form>
</div>
<script type="text/javascript"><!--
$( document ).ready(function() {
var id = 'newsletter_<?php echo $position.$module;?>';
$('#'+id+' .box-heading').bind('click', function(){
$('#'+id).toggleClass('active');
});
$('#formNewLestter').on('submit', function() {
var email = $('.inputNew').val();
$(".success_inline, .warning_inline, .error").remove();
if(!isValidEmailAddress(email)) {
$('.valid').html("<div class=\"error alert alert-danger\"><?php echo $objlang->get('valid_email'); ?><button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div></div>");
$('.inputNew').focus();
return false;
}
var url = "<?php echo $action; ?>";
$.ajax({
type: "post",
url: url,
data: $("#formNewLestter").serialize(),
dataType: 'json',
success: function(json)
{
$(".success_inline, .warning_inline, .error").remove();
if (json['error']) {
$('.valid').html("<div class=\"warning_inline alert alert-danger\">"+json['error']+"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div>");
}
if (json['success']) {
$('.valid').html("<div class=\"success_inline alert alert-success\">"+json['success']+"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button></div>");
}
}
});
return false;
});
});
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
--></script>
This line:
$('.inputNew')
is looking for a class named inputNew. Your HTML doesn't have an element with that name. Your element it looks like has a class of email.
<input type="text" placeholder="Email Here ..." class="form-control email" <?php if(!isset($customer_email)): ?> <?php endif; ?> size="18" name="email">
^^^^^
You also could use the form-control but that doesn't sound unique. An id would be better or you could use the name attribute like this:
$('input[name="email"]')
so change the JS line to:
var email = $('.email').val();
or
var email = $('input[name="email"]').val();
You can read more about these here, https://api.jquery.com/category/selectors/.

AJAX not submitting fom

I am working with a script wherein I should be able to submit a form without page reload with the help of AJAX. The problem is that the form is not submitted to the database. Any help would be appreciated. I had messed with the codes but nothing works for me.
Here is the javascript code:
<script type="text/javascript">
setInterval(function() {
$('#frame').load('chatitems.php');
}, 1);
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var usercontent = $("#username").val();
var namecontent = $("#nickname").val();
var dataString = 'content=' + textcontent;
var userString = 'content=' + usercontent;
var nameString = 'content=' + namecontent;
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "chatitems.php",
data: {
dataString,
userString,
nameString
},
cache: true,
success: function(html) {
$("#show").after(html);
document.getElementById('content').value = '';
$("#flash").hide();
$("#frame").focus();
}
});
}
return false;
});
});
</script>
this is my form:
<form action="" method="post" name="form">
<input type="hidden" class="form-control" id="username" name="username" value="<?php echo $username; ?>" readOnly />
<input type="hidden" class="form-control" id="nickname" name="nickname" value="<?php echo $nickname; ?>" readOnly />
<input type="hidden" class="form-control" id="chat_role" name="chat_role" value="<?php echo $pm_chat; ?>" readOnly />
<input type="hidden" class="form-control" id="team" name="team" value="<?php echo $manager; ?>'s Team" readOnly />
<input type="hidden" class="form-control" id="avatar" name="avatar" value="<?php echo $avatar; ?>" readOnly />
<div class="input-group">
<input type="text" class="form-control" id="content" name="content" />
<span class="input-group-btn">
<input type="submit" name="submit" class="submit_button btn btn-primary" value="Post"></input>
</span>
</div>
</form>
and finally, this is my PHP code:
<?php
include('db.php');
$check = mysql_query("SELECT * FROM chat order by date desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string($_POST['content']);
$nickname=mysql_real_escape_string($_POST['nickname']);
$username=mysql_real_escape_string($_POST['username']);
$ip=mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
mysql_query("insert into chat(message,ip,username,nickname) values ('$content','$ip','$username','$nickname')");
}
$req = mysql_query('select * from chat ORDER BY date desc');
while($dnn = mysql_fetch_array($req))
{
?>
<div class="showbox">
<p><?php echo $dnn['username']; ?> (<?php echo $dnn['ip']; ?>): <?php echo $dnn['message']; ?></p>
</div>
<?php
}
?>
I know there is something wrong with my code somewhere but had spent few days already but no avail. Im hoping that someone would help.
UPDATE
The form is being submitted successfully with this code only data: dataString but when I added the nameString and the userString thats when everything doesnt work as it should. I tried messing around that code but still got nothing.
To find out what is wrong with this you need to establish that:
a) The click event is firing, which you could test by adding a console.log('something'); at the top of that function.
b) The AJAX function is working somewhat correctly, which again you could check by adding a console.log() in the success callback of the AJAX request. You can also check console for errors, e.g if the chatitems.php is 404'ing
c) That all the data you're collecting from the DOM e.g var textcontent = $("#content").val(); contains what you're expecting it to. Again console.log().
d) That the page you're calling is successfully processing the data you're sending across, so die() a print_r() of the $_POST values to check the data it's receiving is in the format your expecting. You also need to add some error handling to your mysql code: https://secure.php.net/manual/en/function.mysql-error.php (or better yet use PDO or MySQLi https://secure.php.net/manual/en/book.pdo.php), which will tell you if there's something wrong with your MySQL code. You can check the return of you're AJAX call (which would include any errors) by console.log(html) in your success callback.
Information you gather from the above will lead you to your bug.
If i understand right, it seem you try to bind event before the button is available. Try (depend on the version of JQuery you use) :
$(document).on('click, '.submit_button', function(){
...
});

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