For one of my websites, I am designing a HTML form with jquery and PHP for sending the data through email.
The Jquery, checks for the empty /blank fields and sends alerts for each filed.
Once the form is submitted with full data, it sends success alert and send the input data through PHP.
Till this point the code works fine.
Once the data is submitted & success alert is shown, I want the html form to be refreshed / reloaded.
But this this not happening, as the form remains with the pre-entered data.
Kindly help me in this please. My Jquery & HTML form is given below.
JQUERY-CODE (with google libs 2.2)
JQUERY CODE
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$("#returnmessage").empty(); // To empty previous error/success message.
// Checking for blank fields.
if (name == '') {
alert(" Please fill your name");
} else if (email == '') {
alert("Please fill your email");
} else if (message == '') {
alert("Please Fill message");
} else { alert("Your form submitted. We will contact you soon.");
$.post("xxx.php", { // To php file.
name: name,
email: email,
message: message
}, function(data) {
$("#returnmessage").append(data);
if (data == "Your form submitted. We will contact you soon.") {
$("#form")[0].reset(); // To reset form fields on success.
}
});
}
});
});
HTML FORM CODE:
<form id="form" method="post" action=" ">
<h4>FEED-BACK FORM</h4>
<p id="returnmessage"></p>
<label>Name: </label>
<input type="text" id="name" /><br>
<label>Email: </label>
<input type="text" id="email" /><br>
<label>Message: </label>
<input type="text" id="message" /><br>
<input type="button" id="submit" value="Submit"/>
</form>
check below js
if (data == "Your form submitted. We will contact you soon.") {
document.getElementById('form').reset(); // To reset form fields on success.
}
Or
if (data == "Your form submitted. We will contact you soon.") {
$('#form').find("input[type=text]").val(""); // To reset form fields on success.
}
you can clear the input fields by setting its value to ""
$("#name").val("");
$("#email").val("");
$("#message").val("");
The problem is most likely with your if statement. The line $("#form")[0].reset(); is correct, move it above the if statement to see it working.
Related
Sorry guys.I'm new in Web Programming as a Student and I like like to focus on Web Development but I found myself in a problem.I tried using JavaScript validation with the form being submitted to a PHP file but i tried using event listeners to help me checking the input field. I wanted to check first if the first name input is filled or not. The event listener help to avoid the form being submitted when the first name is not being filled but when i filled it, the form wont be submitted with a single click to the submit button but needs two clicks for the form to be submitted. Where is the problem?
HTML CODE
`form method="POST" action="form.php" id="form" >
First Name input type= 'text' name= 'firstName' id="firstName">
input type= 'submit' value="Submit Form">`
JAVASCRIPT CODE
var form = document.getElementById("form");
form.addEventListener("submit", eventListerners);
function eventListerners(event){
event.preventDefault();
var firstName = document.getElementById("firstName");
if(firstName.value == ""){
alert("Name cannot be empty");
}
else {
form.removeEventListener("submit", eventListerners);
}
}
You can call submit event in else block:
var form = document.getElementById("form");
form.addEventListener("submit", eventListerners);
function eventListerners(event){
event.preventDefault();
var firstName = document.getElementById("firstName");
if(firstName.value == ""){
alert("Name cannot be empty");
}else{
this.submit();
}
}
<form method="POST" action="form.php" id="form" >
First Name <input type= 'text' name= 'firstName' id="firstName">
<input type= 'submit' value="Submit Form">
Removing event listener is not good practice for submitting form. If user enters valid data then submit form. Or prevent form submission when user enters invalid data.
I have one form which contain multiple email field so this email to be submitted in database but before that it should validate to avoid duplication, (multiple email fields generated by click on add more button which is present in form ).
I have written ValidateEmail script to avoid duplication however it will work for only one email field but not successfull for multiple email field.
issue:
1) if we type email id in first field it will go for validation and check email exist or not if exist disable submit button if not exist enable button.
2) if we type type email id in second field and after validation it return email not exist then it will enable submit button however in first email field contain duplicate email.
3) if all email fields not contain duplicate values then only enable submit button else it should remain disabled..
<form>
<div>
<input type="email" name="email[]" class="email" onblur="validate_email(this)" /> // initially single filed
// This additional email fields created when click on add more button
<input type="email" name="email[]" class="email" onblur="validate_email(this)" />
<input type="email" name="email[]" class="email" onblur="validate_email(this)" />
<input type="email" name="email[]" class="email" onblur="validate_email(this)" />
</div>
<button class="add_more">Add more</button> // this will append extra email fileds
</form>
<script>
// This is the script it will check whether email already exist or not
function ValidateEmail(data) {
var email_id = data.value;
$.ajax({
type: "POST",
url: "<?= base_url('controller') ?>",
data:{
email_id:email_id
},
dataType: 'json',
success: function (response) {
if(response.exist){
// disable submit button and show error
}
else{
//enable submit field and hide error
}
},
error: function (jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
}
</script>
If you're using jQuery for this, you can use event delegation for dynamic inserted/removed element. As of now, those will be the email inputs.
Basically the idea here is:
Get the value of last changed/onblur input element.
Validate for existing email on server side (asynchronous check)
Scan through the current available email inputs, then validate and match each value with the Current Email in step (1).
If found, add a error class to the existing email field
Otherwise, add a valid class to the existing email field
You dont need to pass onblur="validate_email(this)" , this can be done in jquery.
const data = [
'allan#user.com',
'john#user.com',
'ronaldo#user.com',
'sony#user.com',
'victor#user.com',
'matt#user.com',
]
function isEmail(email) {
// eslint-disable-next-line no-useless-escape
return RegExp(/^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i).test(email);
};
function asyncEmailValidate(email) {
return new Promise(function(resolve, reject) {
if (data.includes(email))
return reject('Found duplicated')
return resolve(true);
})
}
$(document).ready(function() {
$(document)
.on('blur',"input.email", function(e) {
// Current email input
var currentEmail = e.target.value,
$emailNode = $(this),
isValid = true;
// Validate email
if (!isEmail(currentEmail))
return;
// Validate email on server side first,
// If found no existing email, then check
// siblings email for duplicates
var serverResult = asyncEmailValidate(currentEmail);
serverResult
.then(function(result) {
// There's no existing email with the inputed email. Now
// look up on other available email inputs fields, except
// the current one, and validate with the current email value
var siblingsEmailInputs = $("input.email").not($emailNode);
if (!siblingsEmailInputs)
return;
if (siblingsEmailInputs.length > 0) {
siblingsEmailInputs.each(function(index) {
console.log('input : ', $(this).val())
if ($(this).val() !== "" && $(this).val() === currentEmail) {
isValid = false;
}
});
}
// Finally update the state for the current field
if (isValid) {
$emailNode.addClass('is-valid');
} else $emailNode.addClass('is-error');
})
.catch(function(error) {
$emailNode.addClass('is-error');
console.log('error:', error);
})
});
})
.email.is-error {
border: 1px solid red;
}
.email.is-valid {
border: 1px solid green;
}
.email {
width: 300px;
margin: 5px;
height: 25px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre>
const data = [
'allan#user.com',
'john#user.com',
'ronaldo#user.com',
'sony#user.com',
'victor#user.com',
'matt#user.com',
]
</pre>
<div>
<input type="email" name="email[]" class="email" />
</div>
<div>
<input type="email" name="email[]" class="email" />
</div>
<div>
<input type="email" name="email[]" class="email" />
</div>
<div>
<input type="email" name="email[]" class="email" />
</div>
Those are just the basic way for you to handle email validation and duplicated emails. I think you can take it from here to work on your submit logic.
One quick note, you should leave the ajax submitting process in a separate function, not mixing up with validation process, it will be clearer.
Hope this help
Link working sample: https://codepen.io/DieByMacro/pen/jOOdWMr
Updated:
- I haven't used ajax with jQuery for a while so I'm not sure about the correct syntax, so I've replaced it with a Promised call which works the same as you make an asynchronous request. You can follow the updated version for your reference.
Before I get into the problem details, I still need to tell you about this form I am creating. I have a Registration form and once the user submits the form by clicking the Submit button, it will NOT go directly to a Successfully Registered page. The user will be seeing a Confirmation page prior to that. In this page, the user will see all the data he inputted for him to review. Below it are the Confirm button and the Return button (if user still likes/needs to edit his details, it will then show the form for him to edit once this button is clicked). But here's the thing, the Registration form page and the Confirmation page are in just the same page. What I did is that when the user submits the form, it will hide some elements including the Submit button and then just show the details he inputted. When the user clicks the Return button on the Confirmation page, it will just then show again the hidden fields so the user can edit his details.
What I did in preventing the form from submitting when there are errors is that I disabled the submit button. But it is not working. I am using bootstrap for my form so when there are errors, the input fields' borders would turn red and would obtain a class has-error. Here's what I did:
$("td .form-group").each(function() {
if($(this).hasClass('has-error') == true) {
$('#submit').attr('disabled', false);
} else {
$('#submit').attr('disabled',true);
}
});
But again, it is not working. I also googled some jQueries like the .valid() and .validate() functions but I'm not really sure about it and also didn't work for me.
I also did this code where the Submit button should disable when required fields are still empty. And it is perfectly working:
$('#submit').attr('disabled',true);
$('input[id^="account"]').keyup(function() {
if(($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0)) {
$('#submit').attr('disabled', false);
} else {
$('#submit').attr('disabled',true);
}
});
I hope you understand my problem. I will make it clearer if this confuses you.
What I did in preventing the form from submitting when there are errors is that I disabled the submit button. But it is not working.
When is it checking for errors? It needs to disable the submit button at the same time it is checking for errors. Your code doesn't work because there's no event telling it WHEN to execute. WHEN do you want submit button to be disabled?
Do you want it triggered when the field is validated or when the form is submitted?
You can't really tie it to the submit button unless you want to click it first to validate the form fields, and then again to submit validated fields. Then you'll need to figure out how to tell it that it's been validated like by a class, maybe? Only accept inputs that hasClass('valid')?
below are the changes
$(".form-group").find("td").each(function() {
if($(this).hasClass('has-error')) {
$('input[type="submit"]').prop('disabled', false);
} else {
$('input[type="submit"]').prop('disabled', true);
}
});
Try the following
$('#submit').click(function(){
var error = false;
$("td .form-group").each(function() {
if($(this).hasClass('has-error') == true) {
error = true;
return false; //break out of .each
}
});
return !error;
});
You can achieve this by maintaining 2 sections.
1. Form section
<form id="form1">
<input type="text" id="name" />
<input type="email" id="email" />
<input type="button" id="confirm" value="Confirm" />
</form>
2. Confirm section
<div id="disp_data" style="display: none;">
<lable>Name: <span id="name_val"></span></lable>
<lable>Email: <span id="email_val"></span></lable>
<input type="button" id="return" value="Return" />
<input type="button" id="submit" value="Submit" />
</div>
You have to submit the form by using js submit method on validating the form in confirm section (When the user clicks on submit button)
$("#submit").click(function(){
var error_cnt = false;
if($("#name").val() == '') {
error_cnt = true;
alert("Enter Name");
}
if($("#email").val() == '') {
error_cnt = true;
alert("Enter Email");
}
if(error_cnt == false) {
$("#form1").submit();
} else {
$("#disp_data").hide();
$("#form1").show();
}
Demo
You have to prevent the form from sumition by return back a boolean false so that it will stop the execution.
$('#submit').click(function(){
var ret = (($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0));
if(!ret) return false;
});
If you want to disable the submit button in case of any error you need to monitor the changes of each input fields. so better to give a class name to all those input fields like commonClass
then
function validation_check(){
var ret = (($('#profile-company_name').val().length !=0) && ($('#account-mail_address').val().length !=0) && ($('#account-confirmemail').val().length !=0) && ($('#account-login_name').val().length !=0) && (($('#account-password').val().length !=0)) && ($('#account-confirmpassword').val().length !=0));
return ret;
}
$("#submit").prop("disabled",true)
$(".commonClass").change(function(){
if(validation_check()){
$("#submit").prop("disabled",false)
}
else {
$("#submit").prop("disabled",true)
}
});
please use onsubmit attribute in the form element and write a javascript function to return false when there is any error. I've added fiddle you can try.
HTML FORM
<form action="" method="" onsubmit="return dosubmit();">
<input type="text" id="name" />
<input type="email" id="email" />
<input type="submit" value="Submit" />
</form>
JAVASCRIPT
function dosubmit() {
if(false) { //Check for errors, if there are errors return false. This will prevent th form being submitted.
return false;
} else {
return true;
}
}
Let me know if this fixes your issue.
In PHP, if the text input "cmtx_comment" is empty, on form submit I show a javascript alert. After I press OK in the alert, the values entered by the user in all fields in the form are gone. How can I keep the user entered values, without adding code to the value of the input elements (something like <input type="text" name="something" value="<?php echo $_GET['something'];?>"> ?
if (empty($cmtx_comment)) { //if comment value is empty
echo <<<EOD
<script>
alert('Please enter a comment!');
</script>
EOD;
return false;
} else { //if comment entered
do stuff
Have you tried localStorage and form validation?
HTML:
<form method="post" action="" onSubmit="return saveComment();">
<input type="text" name="cmtx_comment" id="cmtx_comment" value="" />
<input type="submit" value="Save" />
</form>
JavaScript:
document.getElementById("cmtx_comment").value = localStorage.getItem("comment");
function saveComment() {
var comment = document.getElementById("cmtx_comment").value;
if (comment == "") {
alert("Please enter a comment in first!");
return false;
}
localStorage.setItem("comment", comment);
alert("Your comment has been saved!");
location.reload();
return false;
//return true;
}
Example
On first page load, you are presented with:
If you don't enter a comment, you get the alert:
If you do enter a comment, you get a different alert:
The page will then refresh (or post, simply un-comment the return true, and comment the location.reload), and you will still see the contents you posted the first time.
JavaScript code of validation- https://freedigitalphotos.net/images/js/judd-validate.js
We have some new forms on our website which have client side JavaScript validation.
The validation is triggered when the user "defocuses" from the form fields. The validation is a combination of AJAX (checking database for valid user names etc) and JavaScript (checking fields not blank, or contain expected data).
The user has to click the form submit button twice to send the form. It seems that the first click is triggering the field validation but not submitting the form. Clicking for a second time successfully completes the form.
Go to- https://freedigitalphotos.net/images/recover_password.php
Type arifkpi#gmail.com in the email field, and then immediately hit submit. Again, notice that the first click merely validates the input, using AJAX it is checking the email address is in the database. A second click is required.
I want to fix this, so everything will work with a single click.
Instead of calling Ajax validations on focustout event, you can call it on click of your button and if Ajax returns true result then submit form programatically. Refer few sample code lines:
Html Part:
<form method="post" id="registration_form" name="registration_form" action="register.php">
EmailId: <input type="text" id="email_id" name="email_id">
<label class="error" for="username" id="globalErrorUsername"></label>
Username: <input type="text" id="username" name="username">
<label class="error" id="globalErrorEmail"></label>
<button type="button" id="register_btn" name="register_btn">Register</button>
</form>
Js Part:
$("#register_btn").click(function() {
//.valid function is useful when you are using jquery Validate library for other field validation
if ($('#registration_form').valid()) {
var email_id = $('#registration_form').find('#email_id').val(),
username = $('#registration_form').find('#username').val();
$.ajax({
beforeSend: function() {
$('#globalErrorUsername').html('');
$('#globalErrorEmail').html('');
}, //Show spinner
complete: function() { },
type : 'post',
url : 'check-user-existence.php',
dataType :'json',
data : 'email_id=' + email_id + '&username=' + username,
success:function(response) {
if(response.success == 1) {
//submit the form here
$("#registration_form").submit();
} else if (response.error == 1) {
if(response.details.username != undefined) {
$('#globalErrorUsername').show();
$('#globalErrorUsername').html(response.details.username);
}
if(response.details.email_id != undefined) {
$('#globalErrorEmail').show();
$('#globalErrorEmail').html(response.details.email_id);
$('#email_id').focus();
} else {
$('#username').focus();
}
}
}
});
} else {
return false;
}
return false;
});