How do I get a dynamically created ID? - javascript

I'm an absolute beginner in using javascript and ajax and that's why I'm stuck now. I have a while loop in which there are 2 different buttons. Both work, as I imagine, except for one little thing ...
The product-id is always passed only for the first element or, if I change it for the last element.
How can I pass the correct product ID to the script?
This is my PHP file:
<?php while ( $product = $browse->fetch( PDO::FETCH_ASSOC ) ) :
$postid = $product[ 'id' ];
$userid = 1; ?>
<div id="content_<?php echo $postid ?>">
<div id="reload_<?php echo $postid ?>" class="row postfarbe browse">
<form method='post' action="" onsubmit="return add();">
<input type="hidden" id="userid" value="<?php echo $userid ?>" class="input-box">
<input type="hidden" id="productid" value="<?php echo $postid ?>" class="input-box">
<input type="hidden" id="collection" value="1" class="input-box">
<input type="hidden" id="wish" value="0" class="input-box">
<input type="submit" id="submit" value="Add to Collection" class="btn my-2 my-sm-0 btn-outline-dark btn-sm">
</form>
</div>
</div>
<?php endwhile; ?>
My Javascript is:
function add()
{
var userid = document.getElementById("userid").value;
var productid = document.getElementById("productid").value;
var collection = document.getElementById("collection").value;
var wishlist = document.getElementById("wish").value;
if(userid && productid && collection && wishlist) {
$.ajax
({
type: 'post',
url: 'post_collection.php',
data: {
user_id:userid,
product_id:productid,
collection_id:collection,
wishlist_id:wishlist
},
success: function (response) {
$("#content_"+ productid).load(" #reload_" + productid);
}
});
}
return false;
}
</script>
I know that the product id in my example is always the same, but how can I pass the correct one to the script if there are 10 or more entries in the loop?

Your problem is that id is unique and can only be assigned once to a element, like so:
<p id="paragraph"> This is legal </p>
<p id="paragraph"> This is illegal - It is no longer unique </p>
<p class="paragraph"> This is legal </p>
<p class="paragraph"> This is legal </p>
You can access the currently clicked class by using $(this) like so:
$('.paragraph').click(function() {
$(this).html('See, totally legal.');
});
See this example to see this in use.
Your solution needs to add an onclick() method to a button. This then gets the parent() form. You can then find() the class and get the val() from the form data.
Your form was also submitting the action. You need to have a <button> of type button so it does not submit the action. This must also be a class since it will not be unique if you're multiply creating them.
Here is a working example to just re-add your AJAX request too.
$(document).ready(function() {
$('.submit-btn').click(function() {
var elements = {
'userid': $(this).parent().find('.userid').val(),
'productid': $(this).parent().find('.productid').val(),
'collection': $(this).parent().find('.collection').val(),
'wish': $(this).parent().find('.wish').val()
};
console.log("User ID: " + elements.userid);
console.log("Product ID: " + elements.productid);
console.log("Collection: " + elements.collection);
console.log("Wish: " + elements.wish);
// TODO: Add your AJAX request using these elements
});
});
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- This will be generated by PHP -->
<form method='POST'>
<input hidden class="userid input-box" value="1">
<input hidden class="productid input-box" value="1">
<input hidden class="collection input-box" value="1">
<input hidden class="wish input-box" value="1">
<button type="button" class="submit-btn btn my-2 my-sm-0 btn-outline-dark btn-sm"> Add to collection </button>
</form>
<!-- This will be generated by PHP -->
<br />
<form method='POST'>
<input hidden class="userid input-box" value="2">
<input hidden class="productid input-box" value="2">
<input hidden class="collection input-box" value="2">
<input hidden class="wish input-box" value="2">
<button type="button" class="submit-btn btn my-2 my-sm-0 btn-outline-dark btn-sm"> Add to collection </button>
</form>
Your AJAX Data will look like this:
data: {
user_id: elements.userid,
product_id: elements.productid,
collection_id: elements.collection,
wishlist_id: elements.wish
}
Your PHP code could look like this:
<?php foreach($browse->fetchAll(PDO::FETCH_ASSOC) as $product):
$id = $product['id'];
$productDd = $product['product_id'];
$productCategory = $product['category']; // TODO: change to your column nanme
$productWishList = $product['wish']; ?>
<div class="content_<?= $id; ?>">
<div class="reload_<?= $id; ?> row postfarbe browse">
<form method='POST'>
<input hidden class="userid input-box" value="<?= $id; ?>">
<input hidden class="productid input-box" value="<?= $productCategory; ?>">
<input hidden class="collection input-box" value="<?= $productCollection; ?>">
<input hidden class="wish input-box" value="<?= $productWishList; ?>">
<button type="button" class="submit-btn btn my-2 my-sm-0 btn-outline-dark btn-sm"> Add to collection </button>
</form>
</div>
</div>
<?php endforeach; ?>

I read your code , You want to have multiple entries and want to read / fetch dynamically generated Form's Feilds in the common JS Function Add which is currently referring to FIRST FOUND ELEMENT IN RENDERED HTML - Thats the reason you are getting the same value each time.
You need to alter the logic with little tric - Pass something uniqueness in argument of ADD function
<form method='post' action="" onsubmit="return add(<?php echo $postid; ?> );">
<input type="hidden" id="<?php echo $postid; ?>_userid" value="<?php echo $userid ?>" class="input-box">
<input type="hidden" id="<?php echo $postid; ?>_productid" value="<?php echo $postid ?>" class="input-box">
<input type="hidden" id="<?php echo $postid; ?>_collection" value="1" class="input-box">
<input type="hidden" id="<?php echo $postid; ?>_wish" value="0" class="input-box">
<input type="submit" id="<?php echo $postid; ?>_submit" value="Add to Collection" class="btn my-2 my-sm-0 btn-outline-dark btn-sm">
NOW read uniquely in ADD Function
function add(post_id){
var userid = document.getElementById(post_id+"_userid").value;
var productid = document.getElementById(post_id+"_productid").value;
var collection = document.getElementById(post_id+"_collection").value;
var wishlist = document.getElementById(post_id+"_wish").value;
### Your code as it is ...
}
Hope this make you sense How i have generated in Loop Unique ELEMENT ID and pass same ID in the function as Argument to fetch them in JS.

Related

prevent form form submitting when if min and max condition is not fullfilled

I am using javascript to display an error when user click on form submit button if the number entered is not in between min and max. The issue is when you click submit button the form will submit regardless. Can you please look at the code below and tell me what I need to add. I need to prevent form from submitting if the min and max condition is not fulfilled.
this is my PHP codes
<div class="clearfix"></div>
<form action="store_items.php" method="post" name="cartform">
<div class="col-12 form-group">
<div class="row">
<div class="col-3">
<input type="hidden" name="cart_name" value="<?php echo $row['product_title']; ?>">
<input type="hidden" name="cart_image" value="<?php echo $row['product_photo']; ?>">
<input id="quantity"type="number" name="cart_qty" step="1" class="form-control text-center" onchange="restrictValue(this,<?php echo $min; ?>, <?php echo $max; ?>)">
<small class="float-right"><?php echo $row['product_unit']; ?></small>
<input type="hidden" name="cart_unit" value="<?php echo $row['product_unit']; ?>">
<input type="hidden" name="cart_price" value="<?php echo $row['product_price']; ?>">
<input type="hidden" name="product_id" value="<?php echo $row['id']; ?>">
<input type="hidden" name="seller_id" value="<?php echo $row['seller_id']; ?>">
</div>
<div class="col-9">
<input id="addtocart" class="btn btn-block addtocart" type="submit" value="Add to cart" name="addtocart" <?php if($row['product_status'] == 0) echo 'disabled="disabled"'; ?> >
</div>
</div>
</div>
</form>
this is the javascript
<script type="text/javascript">
function restrictValue(inputElement,minimum,maximum)
{
let value = inputElement.value;
if (value < minimum) {
value = minimum;
alert('Your order has not reach the minimum order quantity');
return false;
}
if (value > maximum) {
value = maximum;
alert('Your order has exceed the avaliable stock');
return false;
}
inputElement.value = value;
}
</script>
You don't need to prevent form submission! You can specify the min and max attribute on <input type="number"> and it will prevent users from entering in anything outside those bounds!
<input id="quantity"type="number" name="cart_qty" step="1" class="form-control text-center" min="<?php echo $min; ?>" max="<?php echo $max; ?>">
But, if you really want to prevent form submission...
<form onsubmit="doValidate">
...
</form>
<script>
function doValidate(event) {
event.preventDefault();
// validate your inputs
};
</script>
You are trying to prevent submission of form, for that you have to look into onSubmit event of form
Here we can add id to form
<div class="clearfix"></div>
<form action="store_items.php" method="post" name="cartform" id="cartfrom">
<div class="col-12 form-group">
<div class="row">
<div class="col-3">
<input type="hidden" name="cart_name" value="<?php echo $row['product_title']; ?>">
<input type="hidden" name="cart_image" value="<?php echo $row['product_photo']; ?>">
<input id="quantity"type="number" name="cart_qty" step="1" class="form-control text-center" onchange="restrictValue(this,<?php echo $min; ?>, <?php echo $max; ?>)">
<small class="float-right"><?php echo $row['product_unit']; ?></small>
<input type="hidden" name="cart_unit" value="<?php echo $row['product_unit']; ?>">
<input type="hidden" name="cart_price" value="<?php echo $row['product_price']; ?>">
<input type="hidden" name="product_id" value="<?php echo $row['id']; ?>">
<input type="hidden" name="seller_id" value="<?php echo $row['seller_id']; ?>">
</div>
<div class="col-9">
<input id="addtocart" class="btn btn-block addtocart" type="submit" value="Add to cart" name="addtocart" <?php if($row['product_status'] == 0) echo 'disabled="disabled"'; ?> >
</div>
</div>
</div>
</form>
In js you can listen to submit event, do validation whatever you want
<script type="text/javascript">
function restrictValue(inputElement,minimum,maximum)
{
let value = inputElement.value;
if (value < minimum) {
value = minimum;
alert('Your order has not reach the minimum order quantity');
return false;
}
if (value > maximum) {
value = maximum;
alert('Your order has exceed the avaliable stock');
return false;
}
inputElement.value = value;
}
function logSubmit(event) {
if(!restrictValue(inputElement,minimum,maximum)) {
event.preventDefault();
}
}
const form = document.getElementById('form');
form.addEventListener('submit', submit);
</script>
You can refer this for onSubmit event.
There are multiple ways you can solve this problem.
You can add a disabled attribute on the submit button. Remove this attribute until all the fields in the form are valid and your form submission is prevented. This might be a bit cumbersome because you'll need to watch for changes on all the form fields and then apply or remove the attribute.
Create a custom submit function using js and attach this as the onsubmit event handler. But you'll need an understanding of ajax calls. eg:
function handleSubmit(evt) {
evt.preventDefault(); // this will prevent the form from submitting
if(allFormFieldsAreValid) {
await fetch('/post-url', // the route you want to post data to
{
method: 'POST',
body: JSON.stringify(data) // the form data
}).then(function (data){
location.replace('/some-url'); // you can redirect to your disered route
});
}
}
<form onsubmit="handleSubmit">
...
</form>

How do you pass a variable into a html submit and a php isset to allow them to match up?

I am very new to PHP and don't know how to match the name of the submit button to the argument inside the $_POST. $email is a string variable. I echo it to make it be the name of the input button and I also set it as the argument of $_POST. But this does not work. Can anybody tell me why?
<tr>
<form method="post" action="">
<input type="submit" name="<?php echo $email?>" value="Approve" class="btn btn-primary">
</form>
</tr>
<?php
if(isset($_POST[$email])) {
echo "z";
}
?>
You need <input type="hidden"> with name="email" and value="PHP variable value" with submit button name="action" with value="Approve"
<form method="post" action="">
<input type="submit" name="action" value="Approve" class="btn btn-primary">
<input type="hidden" name="email" value="<?php echo $email; ?>"/>
</form>
Then after posting it you can just check for the action and email
<?php
if (#$_POST['action'] && $_POST['email']) {
if ($_POST['action'] == 'Approve') {
echo $_POST['email'];
}
}
?>

PHP Form check if PHP x + y > z before submit

I have the following variables:
$aantalcompleet
$ready
$totaalaantal
$aantalcompleet is a value get from DB.
$totaalaantal is also a value get from DB.
$ready is the value get from the form.
I want to check if $aantalcompleet + $ready > $totaalaantal before submit the form.
If this sum is TRUE, I want to get a confirm message with "Continue or Cancel".
If the sum is FALSE, the form can sumbit without message.
my form:
<form action="" method="POST">
<div class="col-lg-3">
<div class="input-group">
<span class="input-group-btn">
<button class="btn btn-default" type="button" name="reset_form" value="Reset Form" onclick="this.form.reset();"><i class="fa fa-trash-o"></i></button>
</span>
<input type="number" class="form-control" name="complete" id="complete" value="" placeholder="0">
<input type="hidden" name="machine" value="<?php echo $machine;?>">
<input type="hidden" name="base" value="<?php echo $base;?>">
<input type="hidden" name="lot" value="<?php echo $lot;?>">
<input type="hidden" name="split" value="<?php echo $split;?>">
<input type="hidden" name="sub" value="<?php echo $sub;?>">
<input type="hidden" name="seq" value="<?php echo $seq;?>">
</div>
</div>
<button class="btn btn-default" style="height:35px;width:200px" type="submit" value="gereed" name="gereed">Gereed</button>
Add this to your page somewhere in <head>
<script>
function onsubmit(event){
if($aantalcompleet + $ready > $totaalaantal){
if(!confirm('Continue or Cancel')){
event.preventDefault();
return false;
}
return true;
}
return true;
}
</script>
Assuming your PHP variables $aantalcompleet, $totaalaantal, and $ready are available in the same file with your form, place the following code to a place where those variables have their expected values (i.e. they are filled with the values from database, maybe just after your sql query if any)
<script>
var $aantalcompleet = <?php echo $aantalcompleet; ?>;
var $totaalaantal = <?php echo $totaalaantal; ?>;
var $ready = <?php echo $ready; ?>;
</script>
Then add onsubmit="return onsubmit(event)" to your form tag, like
<form action="" method="POST" onsubmit="return onsubmit(event)">

Submitting multiple HTML forms with one button (JQuery/Ajax)

I've seen many of the other questions that involve this concept, however many of them suggest just using JQuery, which I tried multiple ways with no success.. I've never used Ajax, and this seems to be the best way to go about this, can anyone help me out with how to implement this? (Ajax or JQuery or however..) Below is the code of the two forms I'm using; following it will be general Javascript idea I was trying to implement, however, I did try many variations of it. I tried using timeouts, and functions such as preventDefault(); and stopPropagation(); all with no luck..
<div container="row-fluid">
<!-- This button appears if there are any items in stock within this warehouse -->
<div class="span2" style="<?php if($row_pending['Wh'.$row_pending['DefaultWh'].'Net'] > 0){}else{echo "display:none;";}?>">
<form method="post" name="ATCForm" id="ATCForm1">
<input id="qtywh1" type="hidden" name="qty" value="">
<input type="hidden" name="wh" value="<?php echo $row_pending['DefaultWh'];?>">
<input type="hidden" name="ot" value="ship">
<input type="hidden" name="net" value="<?php echo $row_pending['Wh'.$row_pending['DefaultWh'].'Net']; ?>">
<button class="btn btn-primary btn-ac" name="ATC" id="ATC1" type="submit" onclick="submitBoth()" value="ATC">Add to Cart</button>
</form>
</div>
<!-- This button appears if there are ZERO items in stock within this warehouse -->
<div class="span2" style="<?php if($row_pending['Wh'.$row_pending['DefaultWh'].'Net'] <= 0){}else{echo "display:none;";}?>">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="ATCForm" id="ATCForm1b">
<input id="qtywh1b" type="hidden" name="qty" value="0">
<input type="hidden" name="wh" value="<?php echo $row_pending['DefaultWh'];?>">
<input type="hidden" name="ot" value="backorder">
<input type="hidden" name="net" value="<?php echo $row_pending['Wh'.$row_pending['DefaultWh'].'Net']; ?>">
<button class="btn btn-primary btn-bo" name="ATC" id="ATC1b" type="submit" value="ATC">Add to Backorder</button>
</form>
</div>
</div><!-- row-fluid -->
Basic Javascript Logic:
<script>
$(document).ready(function{
function submitBoth(){
document.getElementById('ATCForm1').submut();
document.getElementById('ATCForm1b').submit();
}
});
</script>

AJAX: Form Submit to post comments

I'm having an issue getting a form to submit and display the comment without the page refreshing (in-place) but when I click on the button, it takes me to the top of the page but does not perform any actions, does not insert into the database and thus does not display the comments in the page.
It is supposed to place the comment in the appropriate place with a fade effect.
Credits and Demo for the script: Original Script Here
The script provided int he link above, works if I try it as it comes but I had to modify it to fit my needs and this is what I have.
The Form:
<div class="comment-form">
<form id="form" action="" method="post">
<div class="top-form">
<span class="parent name">
<input class="field" type="hidden" name="Name" value="<?php echo $_SESSION["UserName"]; ?>" />
<input class="field" type="text" name="Name" value="<?php echo $_SESSION["UserName"]; ?>" disabled="disabled">
</span>
<span class="parent name">
<input class="field" type="hidden" name="ID" value="<?php echo $_SESSION["UserID"]; ?>" />
<input class="field" type="text" name="ID" value="<?php echo $_SESSION["UserID"]; ?>" disabled="disabled">
</span>
<span class="parent last">
<input class="field" type="hidden" name="PageID" value="<?php echo $_GET['PageID']; ?>" />
<input class="field" type="text" name="PageID" value="<?php echo $_GET['PageID']; ?>" disabled="disabled">
</span>
<div class="clear"></div>
</div>
<div class="bottom-form">
<label>Choose an Option</label>
<select id="commentbox" name="comment" class="bs-select form-control">
<option disabled selected value> -- Options -- </option>
<option value="First Option">First Option</option>
<option value="Second Option">Second Option</option>
<option value="Third Option">Third Option</option>
</select>
<button class="btn btn-icon submit" name="btn-sumbit" type="submit" id="submit" value="Post Message"><span class="icon"></span>Post Message</button>
</div>
</form>
</div>
<div class="comments">
<div class="section-title">
<h3>Messages</h3>
</div>
<ul class="level-1">
<div class="comment-block">
<?php echo $postedcomments; ?> <!-- loads previous comments on page load. it works. -->
</div>
</ul>
</div>
The script
located in the same page as the form.
<script>
$(document).ready(function(){
var form = $('form');
var submit = $('#submit');
form.on('btn-submit', function(e) {
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'data/queries/comment-insert.php',
type: 'POST',
cache: false,
data: form.serialize(), //form serialized data
beforeSend: function(){
// change submit button value text and disabled it
submit.val('Posting...').attr('disabled', 'disabled');
},
success: function(data){
// Append with fadeIn see http://stackoverflow.com/a/978731
var item = $(data).hide().fadeIn(800);
$('.comment-block').append(item);
// reset form and button
form.trigger('reset');
submit.val('Post Message').removeAttr('disabled');
},
error: function(e){
alert(e);
}
});
});
});
</script>
The Query
comment-insert.php
<?php
if (isset( $_SERVER['HTTP_X_REQUESTED_WITH'] )):
include_once 'include/dbconfig.php';
include_once 'include/dbconnection.php';
$conn = dbconnect();
if (!empty($_POST['comment'])) {
$Name = mysqli_real_escape_string($conn, $_POST['Name']);
$PageID = mysqli_real_escape_string($conn, $_POST['PageID']);
$ID = mysqli_real_escape_string($conn, $_POST['ID']);
$Comment = mysqli_real_escape_string($conn, $_POST['comment']);
$sql = "INSERT INTO comments
(PageID, PosterID, PosterName, PostDate, Comment)
VALUES
('$PageID', '$ID', '$Name', now(), '$Comment')";
mysqli_query($conn, $sql) or die("Error: ".mysqli_error($conn));
}
?>
<li><span class='comment'>
<span class='picture'>
<span><img src='users/images/<?php echo $_SESSION['Image'] ?>'></span>
</span>
<span class='content'><span class='title'><b><?php echo $Name ?></b>, Said:</span><br><?php echo $Comment ?></span>
<span class='clear'></span>
</span>
</li>
<?php
mysqli_close($conn);
endif?>
This works:
$(document).ready(function() {
//var form = $('#form');
//var submit = $('#submit');
$('#submit').on('click', function(e) {
e.preventDefault();
// the rest of your code goes here
})
});
Your jQuery event handler refers to an non-existent jQuery object. Try replacing the first line of the event handler with this:
form.on('submit', function(e) {

Categories

Resources