i am making a registration form in which php code and html form are in the same page , and i have also have a java script which validate the fields, but if the validation is done, i need to post the data by calling php and submit in database
if(isset($_POST['Name'])){
$order = "INSERT INTO `reg_form`(`Name`) VALUES ('$_POST[Name]')";
$result = mysql_query($order, $db2);
if (!$result) {
echo("<br>Input is failed");
} else {
echo 'Regestered successfully !!!';
}
}
<form name="register" id="register" class="b1 f_l" action="register.php" method="post">
<div class="input-group" style="padding-top: 20px;">
<span class="label_1">Name </span>
<input type="text" class="inp_t" placeholder="Your Name" name="Name" id="name" required>
</div>
<div style="padding-top: 20px;">
<button type="submit" class="btn btn-primary register" value="submit" >Submit</button>
</div>
</form>
<script language=JavaScript>
$('#register').validator()
.submit(function(e){
var form = $(this);
var valid = form.validator({messageClass: "alert alert-danger validate_error", position: 'center right'});
if (valid.data("validator").checkValidity()){
alert('not working');
}// VALID
e.preventDefault();
return false;
});// SUBMIT
</script>
So you only want to prevent the default action if the form is not validated properly:
if (valid.data("validator").checkValidity())
{
// Assuming this means Validation failed
alert('not working');
e.preventDefault();
return false;
}
else
{
// It's working, let the submission go through
return true;
}
Now you need to give your submit button a name so that PHP can know about it
<button type="submit" name='submit-btn' class="btn btn-primary register" value="submit" >Submit</button>
And lastly you need to update your PHP script to handle the form submission.
Put this script at the top of your register.php file since that's where your form is submitting to, and since you're submitting via POST, check the post array:
// Submit button value check here
if(isset($_POST['submit-btn'] && $_POST['submit-btn'] == "submit")
{
// Handle your form submission here
// Read the data from the $_POST array using the name you gave to the form elements
// Create a database connection and store your data in the database
}
You should write "return true" some where in your JS function for the form to submit. If the validation is successful then return true from your JS function
You have to call event.preventDefault() only when validation fails. So moving it to else clause.
<script language=JavaScript>
$('#register').validator()
.submit(function(e){
var form = $(this);
var valid = form.validator({messageClass: "alert alert-danger validate_error", position: 'center right'});
if (valid.data("validator").checkValidity()){
alert('not working');
return true;
}// VALID
else {
e.preventDefault();
return false;
}
});// SUBMIT
</script>
call the validator function using onClick="validate()" and when the validation is successful, submit the form with document.getElementById("register").submit();
Related
Hi successfully made a form where there are two submit buttons.
I needed two buttons because I need each button to take the form to a different place, while get/post the information in the first form.
This is how I did it
Javascript:
function submitForm(action) {
var form = document.getElementById('form1');
form.action = action;
form.submit();
}
<form id="form1" method="post" >
<div class="f-row">
<label for="pick">Pick-Up Address</label>
<input type="text" input name="pick" required value="<?php echo isset($_POST['pick']) ? $_POST['pick'] : ''; ?>"/>
</div>
<input type="button" onclick="submitForm('page2.php')" class="btn small color left" value="ADD ANOTHER STOP" />
<input type="button" onclick="submitForm('page3.php')" class="btn medium color right" value="Continue" />
</form>
It works, both buttons submits to the relevant pages.
But now there is one problem I can't seem to fix, previously if the form was not filled, and i clicked submit, it would ask me to fill up the required fields, now it does not anymore.
If required fields are not filled up, it still submits the form.
I need button 1 to not require required fields to be filled up, and button 2 to require it as button 2 submits the form, while button 1 brings it to a new form to fill up with other details before they submit from there.
Anyone know of a way I can sort this?
You can try this: <input type="text" name="pick" id="pick" required/> and in the javascript
function submitForm(action) {
var form = document.getElementById('form1');
form.action = action;
if (document.getElementById('pick').value) {
form.submit();
}}
else{
alert('Please fill the required field!');}
You just need to use jquery to validate the form when the first button is clicked and you can use formaction attribute on the button to specify where the button should go when it's clicked.
$('document').ready(function(){
$('#btn1').on('click',function(){
var pick = $('input[type="text"][name="pick"]').val();
if(pick == ""){
alert("enter pick");
return false;
}else{
$(this).submit();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post" >
<div class="f-row">
<label for="pick">Pick-Up Address</label>
<input type="text" name="pick" value="your value">
</div>
<button type="submit" formaction="page2.php" class="btn small color left" id="btn1">ADD ANOTHER STOP</button>
<button type="submit" formaction="page3.php" class="btn medium color right">Continue</button>
</form>
You could use jQuery for this.
if ($('#something').length)
This will check if there exist an element with the id 'something', but not if it is empty or which value it has.
To check this you can use:
if($('#something').val().length>0)
or
if($('#something').val() != "")
Do with it what ever is needed.
You could even add this check within your submitForm function just above the current code.
Try this:
<script>
function submitForm(action) {
var a = $("input[name=pick]").val();
if(a) {
var form = document.getElementById('form1');
form.action = action;
form.submit();
} else {
alert('please fill the required field');
return false;
}
}
</script>
Using this way(simple way):--
<form id="myForm" name="myForm" onSubmit="encriptar_rc4();return false;">
<input type="submit" name="submitOne" value="submitOne" class="submitButton" />
<input type="submit" name="submitTwo" value="submitTwo" class="submitButton" />
</form>
<script>
$(function(){
$(".submitButton").click(function(e){
alert($(this).attr("name"));
});
encriptar_rc4();{
alert('hola');
}
});
</script>
I am working on a website for my app development class and I have the weirdest issue.
I am using a bit of JQuery to send form data to a php page called 'process.php, and then upload it to my DB. The weird bug is that the page reloads upon submitting the form, and I cannot or the life of me figure out how to make the JQuery go on in just the background. That is sorta of the point of using JQuery in the first place haha. Anyways, I will submit all relevant code, let me know if you need anything else.
<script type="text/JavaScript">
$(document).ready(function () {
$('#button').click(function () {
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
</script>
<div class= "main col-xs-9 well">
<h2 style="color: black" class="featurette-heading">Join our mailing list!</h2>
<form id="main" method = "post" class="form-inline">
<label for="inlineFormInput">Name</label>
<input type="text" id="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<label for="inlineFormInputGroup">Email</label>
<div class="input-group mb-2 mr-sm-2 mb-sm-0">
<input type="text" id="email" class="form-control" id="inlineFormInputGroup" placeholder="janedoe#email.com">
</div>
<!--Plan to write success message here -->
<label id="success_message"style="color: darkred"></label>
<button id ="button" type="submit" value="send" class="btn btn-primary">Submit</button>
</form>
This is my php if its relevant:
<?php
include 'connection.php';
$Name = $_POST['name'];
$Email = $_POST['email'];
//Send Scores from Player 1 to Database
$save1 = "INSERT INTO `contact_list` (`name`, `email`) VALUES ('$Name', '$Email')";
$success = $mysqli->query($save1);
if (!$success) {
die("Couldn't enter data: ".$mysqli->error);
echo "unsuccessfully";
}
echo "successfully";
?>
This is a screenshot of the log:
The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
Use <button type="button"> to override default submission behavior
Use event.preventDefault() in the onSubmit event to prevent form submission
Solution 1:
Advantage: simple change to markup
Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?
Insert extra type attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Solution 2:
Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
Better variant:
In this improvement, we listen to the submit event emitted from the <form> element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:
The name attribute is required for .serialize() to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="janedoe#email.com">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
clear the previous state when loading the page.... add this to document.ready function.
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
I want to verify the inputs by javascrpit function perform() and move to a php page named i.php to save the datas in the databasse.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="i.php" method="post">
<br>
Name <input type="text" name="name" id="name" >
<span id="err"></span>
</br>
<br>
Password <input type="Password" name="Password" id="password">
<span id="perr"></span>
</br>
<br>
Gender
<input type="radio" name="gender" id="gender" value="male">Male
<input type="radio" name="gender" id="gender" value="female">Female
</br>
<br>
Department <select name="department" id="department">
<option>------</option>
<option>ECE</option>
<option>BBA</option>
<option>ENG</option>
</select>
</br>
<br>
<button name="btn" type="button" id="btn" onclick="perform()" >Button</button>
<input type="submit" name="submit" value="Submit">
<input type="reset" name="reset" value="Clear">
</br>
</form>
<script type="text/javascript">
function perform()
{
var name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var r =3;
if (name.length==0)
{
document.getElementById('err').innerHTML = "name not found";
r++;
}
if (pass.length<=6 || pass.length>=32 )
{
document.getElementById('perr').innerHTML = "password error";
r++;
}
if(r==3)
{
window.location= "i.php";
}
}
</script>
</body>
</html>*
In i.php page i used var_dump to see the datas whether it has been submitted or not. code of the i.php page:
<!Doctype html>
<html>
<head></head>
<body>
<?php
var_dump($_POST);
?>
</body>
</html>
But its showing arry(0) {}
looks like there nothing that has been submitted.
The issue is that you're redirecting with javascript, and losing the entire form and it's data by doing so.
When the form is valid, submit it rather than redirecting
function perform() {
var _name = document.getElementById('name').value;
var pass = document.getElementById('password').value;
var dept = document.getElementById('department').value;
var gender = document.getElementsByName('gender');
var valid = true;
if (_name.length === 0) {
document.getElementById('err').innerHTML = "name not found";
valid = false;
}
if (pass.length <= 6 || pass.length >= 32) {
document.getElementById('perr').innerHTML = "password error";
valid = false;
}
if (valid) {
document.querySelector('form').submit();
}
}
Note that name is not a good name for variables or form elements, as it already exists in window.name, and that a submit button can not be named submit as it overwrites the named form.submit() function
Another option would be to just remove all the javascript, and use HTML5 validation instead.
Use this code:
<form action="i.php" method="post" onsubmit="perform();">
And in javascript make these changes:
if(r!=3) {
alert('please complete the form';
return false;
}
Javascript doesn't send POST headers with window.location!
By using this code, you don't need to use a button, javascript perform() function runs when the submit button is clicked in the form.
If form values are entered truly, javascript perform() does not return and form submits; else, the function returns and prevents submitting the form.
The problem is you are not submitting the form you are just going to a different page with javascript without passing along any variables. so instead of doing
window.location= "i.php";
you should submit the form like so
document.getElementById("formId").submit();
so you should give the form the id formId
The problem is that you are merely redirecting to the i.php page without posting any data. Replace this line in your JS:
window.location = "i.php";
with this
document.getElementsByTagName('form')[0].submit();
This will find the form in your DOM and submit it along with the data that has been input, preserving the values for your action page.
You also need to rename your submit-button for this to work. Otherwise you will not be able to call the submit function on the form programmatically.
<input type="submit" name="submit-btn" value="Submit" />
should do the trick. However, I don't really see the point of the submit button in addition to your validation/submission button.
Full code sample of the solution here: https://jsfiddle.net/dwu96jqw/1/
by press btn you redirect only and your form dont submitted for transfer via _POST
you should change your code :
<form action="i.php" method="post" id ="form1">
and :
if(r==3)
{
form1.submit();
}
window.location will redirect you to the page, to preserve field values return it
if(r==3)
{
return true;
}
I'm currently creating a subscription form using jQuery. My problem is I want to make this form stay in the same page after user click "SUBSCRIBE" button and when the process is successful, the text on button "SUBSCRIBE" change to "SUBSCRIBED".
Below is the code :
HTML:
<form action="http://bafe.my/sendy/subscribe" class="subcribe-form" accept-charset="UTF-8" data-remote="true" method="post">
<input type="hidden" name="authenticity_token" />
<input type="hidden" name="list" value="ttx7KjWYuptF763m4m892aI59A" />
<input type="hidden" name="name" value="Landing" />
<div class="form-group">
<div class="input-group">
<input type="email" name="email" class="form-control" placeholder="Masukkan email anda" />
<span class="input-group-btn"><button type="submit" class="btn btn-primary">SUBSCRIBE<i class="fa fa-send fa-fw"></i></button></span>
</div>
</div>
</form>
jQuery:
$(".subcribe-form").submit(function(){
var validEmail = true;
$("input.form-control").each(function(){
if ($.trim($(this).val()).length == 0){
$(this).addClass("has-error");
validEmail = false;
} else{
$(this).removeClass("has-error");
}
});
if (!validEmail) alert("Please enter your email to subscribe");
return validEmail;
});
You can use event.preventDefault to prevent the form submission but you also need to send the data to the server so for this you can use jQuery ajax ( see below code )
$(".subcribe-form").submit(function(event){
event.preventDefault()
var validEmail = true;
$("input.form-control").each(function(){
if ($.trim($(this).val()).length == 0){
$(this).addClass("has-error");
validEmail = false;
}
else{
$(this).removeClass("has-error");
}
});
if (!validEmail) { alert("Please enter your email to subscribe");
}else {
//for valid emails sent data to the server
$.ajax({
url: 'some-url',
type: 'post',
dataType: 'json',
data: $('.subcribe-form').serialize(),
success: function(serverResponse) {
//... do something with the server Response...
}
});
}
return validEmail;
});
Add preventDefault so that form submission is prevented
$(".subcribe-form").submit(function(event){
event.preventDefault()
use serialize and post to send your data to desired url
Just handle the form submission on the submit event, and return false:
if using AJAX : (With ajax you can either do that, or e.prenventDefault (), both ways work.)
$(".subcribe-form").submit(function(){
... // code here
return false;
});
If using simple form :
$(".subcribe-form").submit(function(e){
... // code here
e.preventDefault();
});
In my opinion it would be easier to do it using PHP. If you do not want to use PHP, then you can ignore this answer.
If you want to give it a try, you can do the following:
1. Remove the action attribute from the form tag.
2. Write PHP code similar to:
if (isset($_POST['submit']) { // "submit" is the name of the submit button
onSubmit();
}
function onSubmit() {
/* your code here */
}
This is how I stay on the same page, a minimal example using jQuery:
<form id=f
onsubmit="$.post('handler.php',$('#f').serialize(),d=>r.textContent+=rd.innerHTML=d);return false">
<textarea name=field1 id=t>user input here</textarea>
<input type=submit>
</form>
<textarea id=r width=80></textarea>
<div id=rd></div>
The key is to return false from the form onsubmit handler.
I have implemented a simple javascript validation but the validation and the form submission never happen together ...
When i use "onsubmit" (like below) it will goto the next page without validation
if i use "onclick" on the end of the form
<input type="button" name="submit" id="send" value="Search Flights" onclick="return validate_booking_form();" />
</form>
it will validate the input .. but the form wont be submitted even the correct input
This is the code i have used
//Javascript Validation
function validate_booking_form()
{
chk_fromcity();
chk_tocity();
chk_depature_date();
}
function chk_fromcity()
{
var from_city = $('#from_cities').val();
if (from_city == '')
{
$("#from_cities").removeClass('fieldInput');
$("#from_cities").addClass('error');
$("#errormsg_from").fadeTo(200, 1, function()
{
$(this).html('Please Enter a City').addClass('errormsg');
})
}
else
{
$('#from_cities').removeClass('error');
$('#from_cities').addClass('fieldInput');
$("#errormsg_from").fadeTo(200, 1, function()
{
$(this).html('').removeClass('errormsg');
})
}
}
and the form
<form method="POST" action="../controller/booking.php" name="search_flights_names" onsubmit="return validate_booking_form();" >
/// Form content
<div class="form_input_container">
<div class="form_input">
<input type="text" id="from_cities" name="from_city" class="fieldInput" onblur="return chk_fromcity()" />
</div>
</div>
<input type="submit" name="submit" id="send" value="Search Flights" />
</form>
Submit is the proper button to use.
Try putton onsubmit in your form element and have the validation occur there instead of on the click event. That way pressing enter won't bypass all of your validation.
Try using Jquery validate. I think it should pretty much solve your problem
return false from chk_fromcity() to stop the form posting to action.
function chk_fromcity()
{
var from_city = $('#from_cities').val();
if (from_city == '')
{
$("#from_cities").removeClass('fieldInput');
$("#from_cities").addClass('error');
$("#errormsg_from").fadeTo(200, 1, function()
{
$(this).html('Please Enter a City').addClass('errormsg');
});
return false;
}
$('#from_cities').removeClass('error');
$('#from_cities').addClass('fieldInput');
$("#errormsg_from").fadeTo(200, 1, function()
{
$(this).html('').removeClass('errormsg');
})
// return true; // default is true which is why you were passing the validation
}