This question already has answers here:
Checking if form has been submitted - PHP
(9 answers)
Closed 8 years ago.
I want to submit a form with js function, and in the php action page I want to check if the form is submitted or not, here is my code:
<form method="post" action="index.php" name="form1">
<fieldset>
...
</p><div class="clearfix"></div>
<input type="button" id="send1" onclick="validateForm1();" class="comment_submit" value="SUBMIT" name="send1"><p></p>
</fieldset>
</form>
and this is the js:
function validateForm1(){
var name = document.getElementById('fullName');
...
if(isNotEmpty(name))
...
document.forms['form1'].submit();
}
so how I can check if the form is submitted or not, without using if(!empty($_POST)) because I have 2 forms will be submitted to the same action page.
Check whether your fields are filled.
if(!empty($_POST["field1_from_form1"]) && !empty($_POST["field2_from_form1"]) /* && ... */) {
// Form 1 is filled.
}
And for the other form...
if(!empty($_POST["field1_from_form2"]) && !empty($_POST["field2_from_form2"]) /* && ... */) {}
You can also set a hidden input into each form...
<input type="hidden" name="formID" value="1" /> <!-- Form 1 -->
<input type="hidden" name="formID" value="2" /> <!-- Form 2 -->
... and check it:
if(isset($_POST["formID"]) && $_POST["formID"] == 1) // ...
if(isset($_POST["formID"]) && $_POST["formID"] == 2) // ...
For your next questions on Stack Overflow, please use the site's search feature to avoid duplicating already-answered questions.
if($_SERVER['REQUEST_METHOD'] === 'POST') {
if($_POST['myHiddenInput'] === 'form1'){
//process form 1
}
else if($_POST['myHiddenInput'] === 'form2'){
//process form2
}
}
And add some hidden input into form to recognition which one form you posted.
Related
I have this form in html and I want to validate this form when the user press #btnPopup, this button is not a submit one. How can I do this without using jQuery validation plugin, on a click button?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="frmUsers" data-userid="">
<img id="btnClose" src="resources/img/close_window.png">
<h2 id="popupTitle"></h2>
<ul>
<li>
<label for="username">Username:</label>
<input type="text" id="username" name="txtUsername" placeholder="Please select username" required/>
</li>
<li>
<label for="level">Level:</label>
<input type="number" id="level" name="txtLevel" placeholder="Please select level" required/>
</li>
<li>
<label for="registrationStatus">RegistrationStatus:</label>
<select name="txtRegistrationStatus" id="registrationStatus" placeholder="Please select registration status" class="required">
<option value="Registered">Registered</option>
<option value="Unregistered">Unregistered</option>
</select>
</li>
<li>
<label for="registrationDate">RegistrationDate:</label>
<input type="text" id="registrationDate" name="txtRegistrationDate" placeholder="Please select date" required/>
</li>
<div class="btnZone">
<input class="btnDown" type="button" value=" " id="btnPopup" />
<input class="btnDown" type="button" value="Cancel" id="btnCancel">
</div>
</ul>
</form>
You can use ajax by sending your form input in parameters to achieve what your want and attach an event to your button.
$('#btnPopup').on('click', function(){
// Fields validation
if( validation ){
$.ajax({
method: "POST",
url: "your_url",
dataType: 'json',
data: {
'username' : $('#username').val(),
'level' : $('#level').val()
...
}
})
.done(function( result ) {
// Do something
})
.fail(function(result, textStatus) {
// Do something when error happened
});
}else{
// Do something when your validations are bad.
}
});
Don't forget to validate your parameter server side. Validation client side can be by passed easily. After that you can get the server response inside the ajax success callback
You can submit your Form by attaching a "Click" listener on your "#btnPopup" and adding a simple submit inside it:
var myButton = document.getElementById("btnPopup");
myButton.addEventListener("click" , function(){
/*
--Your Validation logic goes here--
*/
// You submit the Form when the Validation is over.
document.getElementById("frmUsers").submit();
});
Now you can write your own Validation functions depending on what you want to validate your form against. A really simple and very basic validation would be to create a general function and validate each field on by one like the following :
function validate(inputField){
var myInputField = document.forms["frmUsers"][inputField].value;
// Add some simple Validation Rules
if(myInputField == null || myInputField == ""){
// Do Something if validation fails [Eg: alert('error!!!');]
return false;
}
}
You can use the above function like :
validate("txtUsername");
You can apparently make a loop and pass through each field in your Form and validate it. Generally there are a lot of ways to validate a Form , the above example will get you in the right track though.
Important: This is a Client-Side validation though. Keep in mind that in 99 cases out of 100 you really need to have a Server-Side validation configured too. Client-Side validation is not 100% secure.
Yes, you can do it. below is sample code which you can tweek and use
function validateForm() {
var x = document.forms["frmUsers"]["registrationDate"].value;
if (x == null || x == "") {
alert("Registration date must be filled out");
return false;
}
}
<input class="btnDown" type="button" value=" " id="btnPopup" onclick="return validateForm();/>
I am using below jsp' form to submit the data. Before submitting I want to apply javascript.
<form name="inventory" method="post" action="<%=request.getContextPath() %>/Tdata_Main" class="form-light mt-20" role="form" onsubmit="return validate(this)">
Now, I have three input tags of 'Submit' type
<input type="submit" name="submit" class="btn btn-two" value="Update Inventory">
<input type="submit" name="submit" class="btn btn-two" value="Add Empty Row">
<input type="submit" id="submitDelete" name="submit" class="btn btn-two" value="Delete Row">
After adding three new columns and filling in the data one by one, I added forth one as shown below. Now, I am in no need of this forth empty row hence I want to delete it. But the javascript code is getting applied here too and asking me to fill in the blank fields.
Below is the javascript code that is getting executed on the onSubmit event initiated from form.
<script type="text/javascript">
function validate(form) {
//alert(form.id);
if(form.id != "submitDelete"){ // NOT WORKING
for(var i = 0; i < form.elements.length; i++){
if(form.elements[i].type == "text"){
if(form.elements[i].value.length == 0 || form.elements[i].value.length == "null"){
alert('No value entered in '+form.elements[i].name+'.');
form.elements[i].focus();
return false;
}
}
}
}
if (confirm("Would you like to proceed!") == true) {
return true;
}
else{
return false;
}
}
</script>
How could I avoid getting this javascript code being applied on Delete using Javascript. Kindly suggest.
Your code works fine. Only one thing you should remove the action attribute from your form element and post that data using javascript only.
Also your delete button is disabled. Enable it and it will work fine
Below is a code of a simple html form and javascript code for checking if the fields are empty or not, when user clicks the submit button.
The problem is, that the form is submitted, even if the necessary fields are not filled in.
As you can see, I am just a beginner with JS coding, so I don't know, if the problem is in if/else statements, somewhere else in the JS code or if the form is not set up properly.
<script>
function preveri(pov){
var preveriime = pov.ime.value;
var preverirojstvo = pov.rojstvo.value;
var preverimail = pov.email.value;
var preverikategorijo = pov.kategorija.value;
if (preveriime == "") {
document.getElementById('imeA').style.display="block";
}
if (preverirojstvo == "") {
document.getElementById('datumA').style.display="block";
}
if (preverimail == "") {
document.getElementById('emailA').style.display="block";
}
if (preverikategorijo == "") {
document.getElementById('kategorijaA').style.display="block";
}
if(preveriime != "" && preverirojstvo != "" && preverimail != "" && preverikategorijo != ""){
document.pov.submit();
}
else{
return false;
}
}
</script>
<h4>OBRAZEC ZA SPLETNE PRIJAVE</h4>
<br/>
<form name="pov" method="POST" action="thankUPage.php">
<input name="ime" type="text" placeholder="Ime in Priimek"></input>
<input name="rojstvo" type="text" placeholder="Datum rojstva"></input>
<input name="email" type="text" placeholder="E-pošta"></input>
<input name="kategorija" type="text" placeholder="Kategorija"></input>
<textarea name="povprasaj" placeholder="Povprašaj"></textarea>
<input type="submit" name="submit" id="submit" value="Pošlji!" onclick="preveri(pov)" />
</form>
<div id="imeA" class="imeA">Obvezno polje!</div>
<div id="datumA" class="datumA">Obvezno polje!</div>
<div id="emailA" class="emailA">Obvezno polje!</div>
<div id="kategorijaA" class="kategorijaA">Obvezno polje!</div>
</div>
Tnx in advance!
You're returning false on the click event. You need to bind your callback function to the form's submit event, so returning false will cancel the form's submission.
Pressing "enter" while in a form field will submit the form and might not trigger the click event on the submit button.
<form name="pov" method="POST" action="thankUPage.php" onsubmit="return preveri(this);" >
I'm having a problem with a simple html login page I made, where when I submit the login form with invalid credentials the form still submits, even though my validation method is executing the "return false" command. I know that this question has been asked a multitude of times here, but none of the answers to those questions have helped me.
My html form is as follows:
<form onSubmit="return validateForm();" method="get" action="TestPage.html">
<div id="centralPoint" class="frame">
<select id="centralPointSelect" data-inline="true" data-mini="true" data-native-menu="false" name="centralPoint"></select>
</div>
<div id="credentialsFrame" class="frame">
<input id="userField" type="text" name="Username" />
<input id="passField" type="password" name="Password" />
</div>
<div id="errorMsg"></div>
<input id="loginBtn" type="submit" value="Login" />
<div id="rememberMe" class="frame">
<input type="checkbox" id="checkbox-1" class="custom" data-mini="true" name="rememberMe" />
<label for="checkbox-1">Keep me signed in</label>
</div>
<div id="forgotPassFrame">
<input id="forgotPass" type="button" data-mini="true" value="Forgot password?" />
</div>
</form>
And here is my javascript method. Note that even if the only line of code in here is "return false;" the form still submits. I've also checked in firebug to make sure that the method is actually being called and that it is indeed returning false, and it all checks out.
function validateForm()
{
var usernameTxt = $("#userField").attr("value");
var passwordTxt = $("#passField").attr("value");
if (usernameTxt == "" || passwordTxt == "" || (usernameTxt == userLbl && passwordTxt == passLbl))
{
$("#errorMsg").html("Please enter a username and password.");
return false;
}
}
Is there something really obvious that I'm missing? I'm not binding the onsubmit event in any way other than what you can see in the html form tag, nor am I assigning any click handler to the submit button.
It might be relevant that I'm using JQuery mobile, is it possible that this is doing something with my form?
If you want to handle form submission on your own, you will need to add the data-ajax="false" attribute to the <form> tag so jQuery Mobile leaves it alone.
To prevent form submissions from being automatically handled with
Ajax, add the data-ajax="false" attribute to the form element. You can
also turn off Ajax form handling completely via the ajaxEnabled global
config option.
Source: http://jquerymobile.com/demos/1.1.0/docs/forms/forms-sample.html
Here is a demo of your form but with the above attribute added: http://jsfiddle.net/XtMw9/
Doing this means that you will have to manually submit your form:
function validateForm()
{
var usernameTxt = $("#userField").val();
var passwordTxt = $("#passField").val();//notice the use of .val() instead of .attr()
if (usernameTxt == "" || passwordTxt == "" || (usernameTxt == userLbl && passwordTxt == passLbl))
{
$("#errorMsg").html("Please enter a username and password.");
return false;
}
var $form = $('form');
$.ajax({
url : $form.attr('action'),
type : $form.attr('method'),
data : $form.serialize(),
success : function (response) { ... },
error : function (a, b, c) { console.log(b); }
});
}
Explanation
This works because by default jQuery Mobile will attempt to submit any form via AJAX. Using the data-ajax="false" attribute we can tell jQuery Mobile to leave a specific form alone so we can submit it on our own.
In validateForm() function, you've used two undefined variables(userLbl and passLbl).
Define value for the variables and check.
I need to validate two things on this form:
1. There are two radio buttons:
• OPTION 1 - On click function hides mm/dd/yyyy fields for OPTION 2
• OPTION 2 - On click function shows mm/dd/yyyy fields which aren't required.
2. Zip code field - Need to validate an array of acceptable zip codes.
I've got this form MOSTLY working aside from a few issues:
1. If you click submit without checking or filling out anything it replaces some of the text on the page with the word "Invalid" and vice versa when valid info has been filled in.
2. It does not go to the next page if valid info has been submitted.
3. It only validates the zipcode field and does not require the radio buttons.
Any help would be greatly appreciated! Thanks!
Test page here: http://circleatseven.com/testing/jquery/zipcodevalidation/
If i have you understand you search for this:
I dont have write a Message with "invalid", i give an alert.
In your HTML add "onsubmit" to your form-Tag:
<form method="post" action="success.php" id="step1" onsubmit="checkdata();">
and add a submit-Button to your form or trigger on your pseudo-submit-button .submit() with jQuery.
In your Javascript you add following function:
function checkdata() {
if ($(":radio:checked").length < 1) {
alert('Please choose an Option!');
return false;
}
zipCodeOk = false;
zipCodes = new Array(75001, 75002, 75006); //Your Zip-Codes
for (var i = 0; i <= zipCodes.length; i++) {
if ($('#enterZip').val() == zipCodes[i]) {
zipCodeOk = true;
break;
}
}
if (!zipCodeOk) {alert('Please enter a valid Zip-Code!');return false;}
}
A friend helped me out.. We ended up using the Jquery validate plugin - here's what we came up with:
<script type="text/javascript">
$(document).ready(function(){
jQuery.validator.addMethod("validZip", function(value) {
var zips=['12345', '23456', '34567', '45678', '56789', '67890', '78901', '89012', '90123', '01234'];
if ($.inArray(value,zips) > -1) {
return true;
} else {
return false;
}
}, "invalid zip");
$("#step1").validate({
rules: {
currentServiceStatus: "required",
enterZip: { validZip : true }
}
});
$('.moveInDates').hide();
$(":radio:eq(0)").click(function(){
$('.moveInDates').hide();
});
$(":radio:eq(1)").click(function(){
$('.moveInDates').show();
});
});
</script>
And here's the html:
<form method="post" action="success.php" id="step1">
<h1>CHOOSE *</h1>
<input name="currentServiceStatus" type="radio" value="Switch Me" /> OPTION 1
<br/>
<input name="currentServiceStatus" type="radio" value="Move-In" /> OPTION 2 (reveals more fields on click)
<div id="dateInputs" class="moveInDates">
<h2>Move-In Date (not required)</h2>
<p><span class="mmddyyyy"><input name="moveInDateMonth" type="text" class="text" id="moveInDateMonth" /> / <input name="moveInDateDay" type="text" class="text" id="moveInDateDay" /> / <input name="moveInDateYear" type="text" class="text" id="moveInDateYear" /></span>
</div>
<hr/>
<h1>ZIP CODE *</h1>
<p>Enter one of the following acceptable Zip Codes:</p>
<p>12345, 23456, 34567, 45678, 56789, 67890, 78901, 89012, 90123, 01234</p>
<input name="enterZip" type="text" class="text" id="enterZip" />
<hr/>
<input type="image" id="submitButton" src="http://circleatseven.com/testing/jquery/zipcodevalidation/library/images/btn_submit.jpg" />
<p><em>* Required</em></p>
</ul>