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

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>

Related

How do I get a dynamically created ID?

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.

validation not working when i am trying to prevent multiple click on submit

i have used class='required' for required validation which is working fine when i remove onClick="this.form.submit(); this.disabled=true;
from submit button.
i want to disable multi click with validation
<form action="<?php echo $this->url('weeklyplan', array('action' => 'add')); ?>" method="post" id='myform'>
<div class="mainformdiv">
<div class= "formelementblock">
<div class="formelement">
<select name="txtdefined_week_id" id="txtdefined_week_id" class="select-block required" onchange="showdateranges()">
<option value="">Select Defined Week</option>
<?php foreach ($definedweeks as $obj) { ?>
<option value="<?php echo $obj->defined_week_id; ?>"><?php echo $obj->start_day . "-" . $obj->end_day; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class= "formelementblock">
<div class="formelement">
<input type="text" readonly="readonly" name="txtstart_date" class="input-text datepickerwidth required" id="txtstart_date" placeholder="Start Date*"/>
</div>
</div>
<div class= "formelementblock last">
<div class="formelement">
<input type="text" readonly="readonly" name="txtend_date" class="input-text datepickerwidth required" id="txtend_date" placeholder="End Date*"/>
</div>
</div>
</div>
<div class="clear"></div>
<div class="form-button">
<div class="button-block">
<input onClick="this.form.submit(); this.disabled=true;" class="button" type="submit" name="button" id="button" value="Save" />
<input class="button" type="button" name="button" id="button" value="Cancel" onclick="window.location = '<?php echo $this->url('weeklyplan', array('action' => 'index')); ?>'" />
</div>
</div>
</form>
$(document).ready(function() {
$("#button").click(function(){
$('#button').attr('disabled',true);
$('#myform').submit();
var no=$("#myform").validate().toShow.length;
if(no!=0){
$('#button').attr('disabled',false);
}
});
});
You are using html5 form validation. If you want to check if the inputs are valid before submit you have to change the:
<input onClick="this.form.submit(); this.disabled=true;" class="button" type="submit" name="button" id="button" value="Save" />
To something like:
<input onClick="checkform(); this.disabled=true;" class="button" type="button" name="button" id="button" value="Save" />
Notice that the button is not a 'submit' type but rather a normal button. With this you can create a javascript function ("checkform()") that checks if the inputs are valid. There is a function in javascript that returns whether an input with the 'required' html5 attribute is valid. This function is:
inputElement.checkValidity()
After you checked if all inputs are valid you can submit the form.

Show values on POST

Working on a really simple form for a district site. I have a really simple form in PHP.
<form method="post">
<fieldset>
<legend>Enter Age and Weight</legend>
<label>Age:</label>
<input type="text" name="age" value="<?php echo #$_POST['age'] ?>">
<label>weight:</label>
<input type="text" name="weight">
<div>
<button class="btn" type="submit" name="action" value="enter">Enter</button>
</div>
</fieldset>
</form>
What I am trying to do is when the user presses the enter button, I want to alert the user of what they have entered.
This is what I have so far in my HTML.
<body onload="document.forms[0].submit()">
<form action="/index.php" onsubmit="" method="POST">
<script>
alert(document.getElementsByName("age").value);
</script>
</form>
</body>
However, I keep seeing "undefined". I am assuming that is happening because on page load my script is being run instead of when the user presses the submit button. Kind of confused how to just do a simple alert. Appreciate any help.
You must insert your code in a function that you must attach to a event handler like onsubmit, something like this:
HTML:
<form method="post" onsubmit="showData();">
JAVASCRIPT:
function showData() {
alert(document.getElementsByName("age")[0].value);
}
I've inserted [0] in your Javascript code because document.getElementsByName returns you an Array of elements, in your case, this Array, obviously contains only one value that is retrievable on the index 0 (first index of any array).
<form method="post" id="myform">
<fieldset>
<legend>Enter Age and Weight</legend>
<label>Age:</label>
<input type="text" name="age" value="<?php echo #$_POST['age'] ?>" id="age">
<label>weight:</label>
<input type="text" name="weight">
<div>
<button class="btn" type="button" name="action" value="enter" onclick="alert(document.getElementById('age').value);document.getElementById('myform').submit()">Enter</button>
</div>
</fieldset>
</form>
Is this what you want?

Closing featherlight upon submitting form

I have a demo-employee.php page that retrieves all the users of the system alongside specific actions that can be performed:
<td><table>
<tr>
<td><i class="fa fa-pencil-square-o"></i></td>
<td></i></td>**
<td><i class="fa fa-trash-o"></i></td>
</tr>
</table>
</td>**
I am using data-featherlight to pop up the page demo-change-passowrd.php, upon clicking the link the user gets this form:
<form id="changePwd" name="formPwd" method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" accept-charset="UTF-8">
<p>Please fill all the mandatory (*) fields.</p>
<div class="question">
<input type="password" name="new_pwd" pattern="^.*(?=.{6,})(?=.*[a-zA-Z])[a-zA-Z0-9]+$" title="Your new Password is required" required/>
<label><?php echo "<font color='red'>New Password(*):</font>" ?></label>
</div>
<div class="question">
<input type="password" name="confirm_pwd" pattern="^.*(?=.{6,})(?=.*[a-zA-Z])[a-zA-Z0-9]+$" title="Confirm Password field is required" required/>
<label><?php echo "<font color='red'>Confirm Password(*):</font>" ?></label>
<span class="required" id="doesNotMatch"></span>
</div>
<center>
<input type="submit" name="submit" onclick="checkPwdMatch();" onsubmit="return closeSelf(this);" value="Submit" />
<input type="hidden" name="user_id" id="user_id" value="<?php echo $user_id; ?>" />
</center>
</form>
I have a method to check if the pwdmatches, and upon successfully submitting the form, it should close with this method which is appended # the bottom of the page
function closeSelf(f){
f.submit()
window.close();
}
Also I moved this from the button to the form onsubmit="return closeSelf(this);", still no luck. Upon submitting the form, it just stays on the demo-change-passowrd.php. I also used window.location.replace to the demo-employeed page instead of window.close(), no luck as well. Can someone help please, I did
$("#myform").submit(function(e) {
//prevent Default functionality
e.preventDefault();
window.close();
Still no luck? am I missing something please?
I added an onsubmit attribute to form that would call 'click' on the close button (which has the class featherlight-close).
<form ... onsubmit="$('.featherlight-close').click()">

Clear textboxes Script not working

I have this form and this Script but the Script doesn't work. I used it like a month ago and it worked, but it doesn't work now.
<form method="post">
<input type="hidden" name="depName" value="<?php echo $_GET['var'];?>">
<input type="hidden" name="personStat" value="Espera">
<div class="input1">FirstName :<input type="text" name="fname" class="in1" value="<?php echo $nombre;?>"> <span class="error1">* <?php echo $nombreErr;?></span> </div>
<div class="input2">LastName :<input type="text" name="lname" class="in2" value="<?php echo $apellido;?>"> <span class="error2">* <?php echo $apellidoErr;?></span> </div>
<div class="input3">2LastName :<input type="text" name="Slname" class="in3" value="<?php echo $segundoAppellido; ?>"> <span class="error1"><?php echo $segundoAppellidoErr; ?></span> </div>
<div class="input4">Student Id :<input type="text" name="studentId" class="in4" value="<?php echo $idEstudiante;?>"> <span class="error2"><?php echo $idEstudianteErr; ?></span> </div>
<input class="buttonClr" type="button" value="Clear">
</form>
Script
<script> //Funtion that works on buttonClr click
$(".buttonClr").live('click',function(){
$(this).parents('form').find('input[type="text"]').val(''); //Clear all textboxes
$('Select').val(''); //Clear the multiple select
});
</script>
I would guess that you have updated your jquery to version 1.7 or above, so live() no longer works. Here's the explanation from jQuery documentation
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
Change your script as below
<script> //Funtion that works on buttonClr click
$(".buttonClr").on('click',function(){
$(this).parents('form').find('input[type="text"]').val(''); //Clear all textboxes
$('Select').val(''); //Clear the multiple select
});
</script>
Working demo: http://jsfiddle.net/16nu4aom/
Try this script, for clearing the input fields:
$(".buttonClr").bind('click',function(){
$(this).parents('form').find('input[type="text"]').val(''); //Clear all textboxes
$('Select').val(''); //Clear the multiple select
});
I suggest you to use reset button instead of JS. Example:
<form method="post">
<input type="hidden" name="depName" value="<?php echo $_GET['var'];?>">
<input type="hidden" name="personStat" value="Espera">
<div class="input1">FirstName :<input type="text" name="fname" class="in1" value="<?php echo $nombre;?>"> <span class="error1">* <?php echo $nombreErr;?></span> </div>
<div class="input2">LastName :<input type="text" name="lname" class="in2" value="<?php echo $apellido;?>"> <span class="error2">* <?php echo $apellidoErr;?></span> </div>
<div class="input3">2LastName :<input type="text" name="Slname" class="in3" value="<?php echo $segundoAppellido; ?>"> <span class="error1"><?php echo $segundoAppellidoErr; ?></span> </div>
<div class="input4">Student Id :<input type="text" name="studentId" class="in4" value="<?php echo $idEstudiante;?>"> <span class="error2"><?php echo $idEstudianteErr; ?></span> </div>
<input class="buttonClr" type="reset" value="Clear">
<!---^^^^^^^-->
</form>
If just want to reset all form fields, you just need to add reset button. That is the simplest way for 1 click resetting button.
<input type="reset" value="Reset"/>

Categories

Resources