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)">
Related
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>
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'];
}
}
?>
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.
Every time I access $_POST on the other page, there is no value. How do we submit post request if the form is in innerHTML?
function edit(firstname){
var firstname_old = document.getElementById("firstname-div")
//Set id="FirstName" to your input field
firstname_old.innerHTML= 'First Name:<input type="text" id="FirstName" name="firstname" value="'+ firstname +'">';
}
<form class="" action="summary.php" method="post">
<div id="firstname-div">
<?php echo "First Name: $firstname<br>"; ?>
</div>
<button type="button" onclick="edit('<?php echo $firstname ?>')">edit</button><br>
<input type="submit" name="submit" value="submit">
</form>
When you are not in "edit-mode" your're putting out just a text.
<?php echo "First Name: $firstname<br>"; ?>
Thist text is inside the form which will be submitted but its not a form-field! To achieve what you want (deliver the content of "firstname" via ajax) you need a "hidden field".
So you put the same value which is shown in the text to a hidden input like this.
<form class="" action="summary.php" method="post">
<div id="firstname-div">
<?php echo "First Name: $firstname<br>"; ?>
</div>
<button type="button" onclick="edit('<?php echo $firstname ?>')">edit</button><br>
<input type="hidden" name="firstname" value="'<?php echo $firstname ?>'">
<input type="submit" name="submit" value="submit">
</form>
What I understand that you want to display a textbox to edit the name on clicking the edit button . Here is one solution for that:-
<script>
$(document).ready(function(){
$("#edit").click(function(){
document.getElementById("firstname-div").style.display = "none" ;
document.getElementById("firstname-div-edit").style.display = "block" ;
});
});
</script>
<HTML>
<form class="" action="summary.php" method="post">
<div id="firstname-div">
<?php echo "First Name: $firstname<br>"; ?>
</div>
<div id="firstname-div-edit" style="display:none;">
<input type="text" name="firstname" value="'<?php echo $firstname ?>'">
</div>
<button type="button" id="edit">edit</button><br>
<input type="submit" name="submit" value="submit">
</form>
</HTML>
Check and let me know if it works for you or not.
I have a script here right now that will display(alert) me the ID from the reaction and the First Name and Last Name. Now I need it that when I press this button it will store the ID in a hidden form input so it will send it to the database.
Script that alerts the data:
<script type="text/javascript">
function printIt(id){
alert(document.getElementById(id).value);
alert(document.getElementById('naam'+id).value);
}
</script>
<form name="formName">
<input type=hidden id="'.$reactie['id'].'" name="abcName" value="'.$reactie['id'] .'"/>
<input type=hidden id="naam'.$reactie['id'].'" name="abcName" value="Reactie op bericht van '.$reactie['voornaam'].' ' .$reactie['achternaam'] .'"/>
<input class="btn btn-primary btn-xs" type=button value="Reageer" onclick="printIt(\''.$reactie['id'] .'\')" />
</form>
Script that sends the form (where the ID needs to be added) to the database:
<?php if(isset($_POST['react_btn'])){ unset($q1); $q1['reactie'] = $app->check_string($_POST['reactie']);
$q1['topic_id'] = $app->check_string($_POST['topicid']);
$q1['klant_id'] = $app->check_string($_POST['klantid']);
$q1['ledenpagina_id'] = $app->check_string($_POST['ledenpaginaid']);
$app->insert_query('reacties', $q1, 'id');
}
?>
<form action="" method="post"> <div class="form-group">
<label for="comment">Reactie:</label>
<textarea class="form-control" name="reactie" rows="3" id="comment"></textarea>
<input type="hidden" name="klantid" value="<?php echo $_SESSION["klant_id"] ?>"> <input type="hidden" name="topicid" value="<?php echo $actieftopicid ?>">
<input type="hidden" name="ledenpaginaid" value="<?php echo $_SESSION["ledenpagina_id"]; ?>">
<input type="hidden" name="onderreactieID" value="<?php echo $reactie; ?>">
<button type="submit" name="react_btn" class="btn btn-primary">Plaats reactie</button>
</div>
</form>
Summary:
I need the data from the first script ($reactie['id']) when you press the button to fill that in some hidden field. That field needs to go to the database.
So it needs to set that javascript in a hidden field somehow. And when you didnt press anybuttons it needs to be a default 0.
Set <input type="hidden" value="0"/> and when no button pressed you get 0 from hidden input(click on Check Value button to see it)
And 'when a button is pressed'(SetID ! button) will set the given id.
it follows:
function setID(iD){
var hidden_input = document.getElementById('my_hidden_input');
hidden_input.value = iD;
alert('The ID given from button is "' + iD + '".');
alert('The new value of my_hidden_input is "' + hidden_input.value + '".');
}
function check(){
alert('The value of my_hidden_input is "' + document.getElementById('my_hidden_input').value + '".');
}
<form>
<input type="hidden" id="my_hidden_input" value="0"/>
<input type="button" value="SetID !" onclick="setID('MyID')" />
<input type="button" value="Check Value" onclick="check()" />
</form>
You should already have a hidden input ready if you otherwise want to set reactieID to 0. You can set the value with javaScript on click event.
console.log("Value of hidden input reactieID = " + document.getElementById('reactieHier').value);
<form name="formName">
<input class="btn btn-primary btn-xs" type=button value="Reageer" onclick="document.getElementById(
'reactieHier').value = '5'; console.log('Value of hidden input reactieID = ' + document.getElementById('reactieHier').value)" />
</form>
<form>
<div class="form-group">
<label for="comment">Reactie:</label>
<textarea class="form-control" name="reactie" rows="3" id="comment"></textarea>
<input type="hidden" name="klantid" value="99">
<input type="hidden" name="topicid" value="99">
<input type="hidden" name="ledenpaginaid" value="99">
<input type="hidden" name="onderreactieID" value="99">
<input type="hidden" name="reactieID" id="reactieHier" value="0">
<button type="submit" name="react_btn" class="btn btn-primary">Plaats reactie</button>
</div>
</form>