I have a form to submit data in to a database through mysql php. I am using validation to check if the fields have values or not. Now I want if validation successful on submit button, hide the submit button and show loading image till the time user do not go to submission successful page.
Validation code is working fine. But problem is in hiding submit and showing loading image.
Validation Code :
$('.msf-form form').on('submit', function(e){
$(".loading").show();
$(".sbmt").hide();
var return_val = true;
console.log('test');
$(this).find('.is_mobile:visible').each(function() {
if( $(this).val() == "" ) {
return_val = false;
$(this).focus().css('border','1px solid #F44336');
$(".error-messages-mobile").text("Your valid Mobile Number is required ").fadeIn();
}
else{
$(this).css('border','0px solid #F44336');
$(".error-messages-mobile").empty().fadeOut();
}
});
$(this).find('.is_otp:visible').each(function() {
if( $(this).val() == "" ) {
return_val = false;
$(this).focus().css('border','1px solid #F44336');
$(".error-messages-otp").text("OTP is required ").fadeIn();
}
console.log(return_val);
if(return_val == true){
return_val = false;
var data = {
countryCode: $('#hiddenCode').val(),
mobileNumber: $('#hiddenNumber').val(),
oneTimePassword: $('#oneTimePassword').val()
};
$.ajax({
url: 'test.com',
type: 'POST',
data: data,
success: function (response) {console.log(response);
if (response == 'NUMBER VERIFIED SUCCESSFULLY') {
$(".error-messages-votp").empty().fadeOut();
$('.msf-form form').unbind('submit');
$('.msf-form form').submit();
return true;
}
else
{
return_val = false;
$(this).focus().css('border','1px solid #F44336');
$(".error-messages-otp").text("Enter valid OTP ").fadeIn();
}
},
error: function (jqXHR, textStatus, ex) { return_val = false;
console.log(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
}
});
if(!return_val){
$(".loading").hide();
$(".sbmt").show();
return return_val;
}
});
Style for loading div :
Code :
<style>
.loading{
display:none;
color:#FF0000;
}
</style>
Html and PHP Form Code:
I have two inputs mobile number and OTP. I want if two of them have values then hide submit button on click and show loading image.
<input type="text" name="number" placeholder="Enter Mobile number" id="number" class="is_mobile" ><br />
<input type="hidden" name="country_code" id="country_code" class="is_vcountrycode" value="91" ><br>
<span class="error-messages-mobile" id="error"></span><br>
<div id="verifyOtpForm" >
<input type="text" name="oneTimePassword" placeholder="Enter OTP" id="oneTimePassword" class="is_otp"><br><br>
<span class="error-messages-otp" id="error"></span><br>
<input type="hidden" name="hiddenCode" id="hiddenCode">
<input type="hidden" name="hiddenNumber" id="hiddenNumber"><br>
</div>
</div>
<button type="submit" class="btn sbmt">Submit</button>
<div class="loading" style="font-size:22px;"><img src="images/loading1.gif"></div>
what is output in console? - console.log(response);
You have to put
if(!return_val){
$(".loading").hide();
$(".sbmt").show();
return return_val;
}
Code in AJAX success and error function.
This code gets executed before AJAX call respond. So try putting it in success and error block.
You have to make following changes
1. Change
<button type="submit" class="btn sbmt">Submit</button>
To
<button type="button" class="btn sbmt">Submit</button>
2. Change
$('.msf-form form').on('submit', function(e){
To
$('.msf-form form').on('click', function(e){
3. Remove
if(!return_val) {
$(".loading").hide();
$(".sbmt").show();
return return_val;
}
4. Change your Ajax else condition
From
else {
return_val = false;
$(this).focus().css('border','1px solid #F44336');
$(".error-messages-otp").text("Enter valid OTP ").fadeIn();
}
to
else {
return_val = false;
$(".loading").hide();
$(".sbmt").show();
$(this).focus().css('border','1px solid #F44336');
$(".error-messages-otp").text("Enter valid OTP ").fadeIn();
}
Related
<form id='formregister' autocomplete='off'>
<input type='text' name='user' maxlength='50' placeholder='* Username'>
<input type='text' name='pass' maxlength='50' placeholder='* Password'>
<input type='text' name='name' maxlength='50' placeholder='Ime'>
<button id='btnregister'>Register</button>
</form>
javascript
$('#btnregister').click(function(){
$.ajax({
url: 'regpro.php',
type: 'post',
data: $('#formregister').serialize(),
success: function(data) {
if (data == 'exists') {
alert ('user already exists'); // after closing form is empty!
}
else if (data =='empty'){
alert ('something is missing'); // after closing form is empty!
}
else{
if (window.confirm('Registration is successfull. Do you wont to login?')){
window.location.href = 'login.php'; // doesn't work
}
else {
window.location.href = 'index.php'; // doesn't work
}
}
}
});
});
So why form inputs become empty after closing alert, and why redirections don't work after confirm dialog is closed ?
You should add event.preventDefault(); to your code:
$('#btnregister').click(function(event){
event.preventDefault();
...
});
This method will disable the default submit action of the form when you click on the button.
I hope you can help me
I have this form
<form action="do_login.php?id=" method=post>
<label>Enter your Frequent Diner ID</label><br>
<div class="shake-id">
<input id="fd-id" class="log-input" type="text" name=loginid value="" maxlength="8" placeholder="Frequent Diner ID" /><br>
</div>
<div class="id-alert" style="display: none;">Your Frequent Diner ID must have 8 digits. Check and try again</div>
<label>Enter your Password</label><br>
<div class="shake-pass">
<input id="pass" class="log-input" type="password" name=password value="" maxlength="20" placeholder="Password" /><br>
</div>
<div class="pass-alert" style="display: none;">Pass wrong</div>
<input type=hidden name=call_from value="login.php">
<input type=hidden name=forward_url value="<?PHP echo urlencode(#$_REQUEST["forward_url"])?>"><br><br>
<input id="test" type=submit value="Login">
</form>
This form execute the file do_login.php (I can not modify this action) but I have added this script before to execute the form:
$('form').submit(function () {
var value = document.getElementById('fd-id').value;
if (value.length !== 8) {
$('.shake-id').effect("shake");
$('.id-alert').fadeIn('slow');
$('#fd-id').addClass('input-wrong');
return false;
}
var value1 = $("#fd-id").val();
var value2 = $("#pass").val();
$.ajaxSetup({url: "check.php",type: 'POST', async: true, data: 'parametro1='+value1+'¶metro2='+value2+'',
success: function(result){
if (result==("OK")){
return true; //here should execute DO_LOGIN.PHP
} else {
$('.shake-pass').effect("shake");
$('.pass-alert').fadeIn('slow');
$('#pass').addClass('input-wrong');
return false; //here should NOT execute the DO_LOGIN.PHP
}
},
error:function(){
alert('dio error');
}
});
$.ajax();
});
This is working properly but the form is still calling to do_login.php. I want to call the form only if the ajax is successfull... I have added return false; and return true; in the ajax but anyway after process keep executing do_login.php
If you see my first lines of the script them execute another verification and return the form false successful but when I use the same in the ajax the return false looks like it doesnt work
Thanks in advance
It is because the ajax request is asynchronous. So the form submitwon't wait for the ajax request to complete and return true/false, since the default action is not prevented the form is submitted.
The solution is to prevent the form submit in the submit handler, then in the ajax handler if the request is successfull then call the submit again.
$('form').submit(function (e) {
//stop form from submitting
e.preventDefault();
var value = document.getElementById('fd-id').value;
if (value.length !== 8) {
$('.shake-id').effect("shake");
$('.id-alert').fadeIn('slow');
$('#fd-id').addClass('input-wrong');
return false;
}
var value1 = $("#fd-id").val();
var value2 = $("#pass").val();
var frm = this;
$.ajax({
url: "check.php",
type: 'POST',
data: 'parametro1=' + value1 + '¶metro2=' + value2 + '',
success: function (result) {
if (result == ("OK")) {
frm.submit();
} else {
$('.shake-pass').effect("shake");
$('.pass-alert').fadeIn('slow');
$('#pass').addClass('input-wrong');
}
},
error: function () {
alert('dio error');
}
});
});
Also note that I have removed the use of ajasSetup as it is not really needed, just use $.ajax() directly
Use e.preventDefault();
Place this just after you form submit function.
I currently have a form at the top of every page on my website that lets the user input the username and password to login.
but Once the button is clicked, I use JQuery AJAX method to submit it to login.php without page refresh where it validates credentials and returns users whether the username / password submitted was valid or invalid.
Finally, the result is returned back to the page the user tried to login on.
I would also like the page to after once there is a successful login, the form disappears and is replaced with "Welcome back, USER!"
Everything works except for I want this to happen without a page reload. Here is what I have so far:-
Display form if session is not set, otherwise say Welcome back, user:-
<div class="user">
<?php
if (isset($_SESSION['logged_user'])) {
$logged_user = $_SESSION['logged_user'];
print("<p>Welcome back, $logged_user!</p>");
}
else {
print('<div class="forms">
<form id="login">
<label>Username <input type="text" name="username" id="username"></label>
<label>Password <input type="text" name="password" id="password"></label>
<input type="submit" class="submit" value="Login" id="login">
<span class="error"></span>
</form>
</div>');
}
?>
</div>
Javascript / AJAX to handle submission:
$(document).ready(function() {
$("#login").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username='+username+'&password='+password;
if(username != '' && password != '') {
$.ajax({
type: "POST",
url: "login.php",
data: dataString,
success: function(responseText) {
if(responseText == 0) {
$("error").html("Invalid login.");
}
else if(responseText == 1) {
window.location = 'index.php';
}
else {
alert('Error');
}
}
});
}
return false;
});
And my login.php does everything fine.
Right now, the only way for my page to update to show the Welcome back message is if I include the line: window.location = 'index.php'; so that the page reloads. But without this, the user will have logged in successfully but will not be able to see this.
Is there a way to do this without AngularJS? This is for a class and we are not allowed to use frameworks, which has been quite frustrating! Thanks!
You can use Dynamic HTML (DHTML).
The success function you don't redirect instead using jquery to change the content.
Something like this:
success: function(responseText) {
if(responseText == 0) {
alert('Invalid login');
}
else if(responseText == 1) {
// Success
$('#login').parent().append('<p>Welcome back, '+username+'!</p>');
$('#login').remove();
}
else {
alert('Another Invalid login');
}
}
The API Login return:
0 if invalid
1 if valid
use this code,
<div class="user">
<div class="after_login" style="display:none">
<?php
$logged_user = $_SESSION['logged_user'];
print("<p>Welcome back, $logged_user!</p>");?>
</div>
<div class = "before_login">
print('<div class="forms">
<form id="login">
<label>Username <input type="text" name="username" id="username"></label>
<label>Password <input type="text" name="password" id="password"></label>
<input type="submit" class="submit" value="Login" id="login">
<span class="error"></span>
</form>
</div>');
?>
</div>
</div>
in script use like this instead of:
window.location = 'index.php';
use below lines,
$('.after_login').show();
$('.before_login').hide();
You have to change some modification in your javascript code as below :
$(document).ready(function() {
$("#login").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username='+username+'&password='+password;
if(username != '' && password != '') {
$.ajax({
type: "POST",
url: "login.php",
data: dataString,
dataType: "json",
success: function(responseText) {
if(responseText.status == 'invalid') {
$(".error").html("Invalid login.");
}
else if(responseText.status == 'valid') {
$('.after_login').html('Welcome back,'+responseText.username);
$('.after_login').show();
$('.before_login').hide();
}
else {
alert('Error');
}
}
});
}
return false;
});
In above example, I have added one extra line dataType: "json", So now you have need to send output in json format from your login.php and also some modification done in success.
$response = array();
// $result variable get result from your database
if(count($result) == 0)
{
$response['status'] = 'invalid';
}else{
$response['status'] = 'valid';
$response['username'] = $result['username'];
}
echo json_encode($response);
exit;
So your success become like that below
success: function(responseText) {
if(responseText.status == 'invalid') {
$(".error").html("Invalid login.");
}
else if(responseText.status == 'valid') {
$('.after_login').html('Welcome back,'+responseText.username);
$('.after_login').show();
$('.before_login').hide();
}
else {
alert('Error');
}
In your login.php, change success condition to output username instead of 1. So responseText will have the username on ajax callback.
Remove the final else condition in your ajax success, and do something like this in the success condition
$('.forms').html('<p>Welcome back, ' + responseText + '!</p>');
PHP:
if (isset($_SESSION['logged_user'])) {
$logged_user = $_SESSION['logged_user'];
//Leave out the print(Welcome...) part, it won't do anything because the page won't be refreshed.
}
else{
exit('1');
}
In the Ajax, don't worry about responseText == 0, just stick with ==1:
success: function(responseText) {
if(responseText == "1") {
alert("Nope");
}
else {
$("#successdiv").html("welcome...");
}
I am trying to validate a form via jquery but after I hit the submit button the message appears, focus works, but only for 1 ms after message disappears and field looses focus.
Jquery Ajax
$(document).on('submit','.subscribe',function(e) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var name = $("#sname").val();
var email = $("#semail").val();
if( name == "" ) {
$("#submess").html('Please enter your name in the required field to proceed.');
$("#sname").focus();
}
else if( email == "" ) {
$("#submess").html('Please enter your email address in the required email field to proceed. Thanks.');
$("#email").focus();
}
else if(reg.test(email) == false) {
$("#submess").html('Sorry, your email address is invalid. Please enter a valid email address to proceed. Thanks.');
$("#email").focus();
}
else
{
e.preventDefault(); // add here
e.stopPropagation(); // add here
$.ajax({ url: 'lib/common-functions.php',
data: {action: 'subscribe',
sname: $("#sname").val(),
semail: $("#semail").val()},
type: 'post',
success: function(output) {
$("#submess").html(output);
}
});
}
});
HTML
<form name="subscribe" class="subscribe">
<div id="submess"></div>
<label class="lablabel">Name:</label><input type="text" class="subscribe-field" id="sname" name="sname"></br>
<label class="lablabel">Email:</label><input type="text" class="subscribe-field" id="semail" name="semail">
<input type="submit" id="ssub" value="Subscribe">
</form>
Where am i mistaking.
Add
e.preventDefault();
After
$(document).on('submit','.subscribe',function(e) {
Your page is reloading, that's the problem.
i.e.
$(document).on('submit','.subscribe',function(e) {
e.preventDefault();
// some more stuff
}
Working fiddle
I am using the following script for validate my contact form.
//submission scripts
$('.contactForm').submit( function(){
//statements to validate the form
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var email = document.getElementById('e-mail');
if (!filter.test(email.value)) {
$('.email-missing').show();
} else {$('.email-missing').hide();}
if (document.cform.name.value == "") {
$('.name-missing').show();
} else {$('.name-missing').hide();}
if (document.cform.phone.value == "") {
$('.phone-missing').show();
}
else if(isNaN(document.cform.phone.value)){
$('.phone-missing').show();
}
else {$('.phone-missing').hide();}
if (document.cform.message.value == "") {
$('.message-missing').show();
} else {$('.message-missing').hide();}
if ((document.cform.name.value == "") || (!filter.test(email.value)) || (document.cform.message.value == "") || isNaN(document.cform.phone.value)){
return false;
}
if ((document.cform.name.value != "") && (filter.test(email.value)) && (document.cform.message.value != "")) {
//hide the form
//$('.contactForm').hide();
//show the loading bar
$('.loader').append($('.bar'));
$('.bar').css({display:'block'});
/*document.cform.name.value = '';
document.cform.e-mail.value = '';
document.cform.phone.value = '';
document.cform.message.value = '';*/
//send the ajax request
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
//hide the graphic
$('.bar').css({display:'none'});
$('.loader').append(data);
});
//waits 2000, then closes the form and fades out
//setTimeout('$("#backgroundPopup").fadeOut("slow"); $("#contactForm").slideUp("slow")', 2000);
//stay on the page
return false;
}
});
This is my form
<form action="mail.php" class="contactForm" id="cform" name="cform" method="post">
<input id="name" type="text" value="" name="name" />
<br />
<span class="name-missing">Please enter your name</span>
<input id="e-mail" type="text" value="" name="email" />
<br />
<span class="email-missing">Please enter a valid e-mail</span>
<input id="phone" type="text" value="" name="phone" />
<br />
<span class="phone-missing">Please enter a valid phone number</span>
<textarea id="message" rows="" cols="" name="message"></textarea>
<br />
<span class="message-missing">Please enter message</span>
<input class="submit" type="submit" name="submit" value="Submit Form" />
</form>
I need to clear the form field values after submitting successfully. How can i do this?
$("#cform")[0].reset();
or in plain javascript:
document.getElementById("cform").reset();
You can do this inside your $.post calls success callback like this
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
//hide the graphic
$('.bar').css({display:'none'});
$('.loader').append(data);
//clear fields
$('input[type="text"],textarea').val('');
});
use this:
$('form.contactForm input[type="text"],texatrea, select').val('');
or if you have a reference to the form with this:
$('input[type="text"],texatrea, select', this).val('');
:input === <input> + <select>s + <textarea>s
$('.contactForm').submit(function(){
var that = this;
//...more form stuff...
$.post('mail.php',{...params...},function(data){
//...more success stuff...
that.reset();
});
});
Simply
$('#cform')[0].reset();
it works: call this function after ajax success and send your form id as it's paramete. something like this:
This function clear all input fields value including button, submit, reset, hidden fields
function resetForm(formid) {
$('#' + formid + ' :input').each(function(){
$(this).val('').attr('checked',false).attr('selected',false);
});
}
* This function clears all input fields value except button, submit, reset, hidden fields
* */
function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
.removeAttr('checked') .removeAttr('selected');
}
example:
<script>
(function($){
function processForm( e ){
$.ajax({
url: 'insert.php',
dataType: 'text',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $(this).serialize(),
success: function( data, textStatus, jQxhr ){
$('#alertt').fadeIn(2000);
$('#alertt').html( data );
$('#alertt').fadeOut(3000);
resetForm('userInf');
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
e.preventDefault();
}
$('#userInf').submit( processForm );
})(jQuery);
function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
.removeAttr('checked') .removeAttr('selected');
}
</script>
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
if(data==<when do you want to clear the form>){
$('#<form Id>').find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
}
});
}
});
http://www.electrictoolbox.com/jquery-clear-form/
Set id in form when you submitting form
<form action="" id="cform">
<input type="submit" name="">
</form>
set in jquery
document.getElementById("cform").reset();
$('#formid).reset();
or
document.getElementById('formid').reset();
Vanilla!
I know this post is quite old.
Since OP is using jquery ajax this code will be needed.
But for the ones looking for vanilla.
...
// Send the value
xhttp.send(params);
// Clear the input after submission
document.getElementById('cform').reset();
}
just use form tag alone, like this :
$.ajax({
type: "POST",
url: "/demo",
data: dataString,
success: function () {
$("form")[0].reset();
$("#test").html("<div id='message'></div>");
$("#message")
.html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function () {
$("#message").append(
"<img id='checkmark' src='images/check.png' />"
);
});
}
});
e.preventDefault();
});
Using ajax reset() method you can clear the form after submit
example from your script above:
const form = document.getElementById(cform).reset();
If you are using a form tag in your form. Then
$("#cform")[0].reset();
This code will work perfectly but in case you are not using any form tag then you can try to set an empty value to each input field Like this.
$('input[type="text"],textarea').val('');