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 am simply trying to log in on a popup log in box. I used AJAX to check whether log in is successful or not. If it is successful move to header location otherwise Give an error.
Code look like this:
<script>
$(document).ready(function () {
$('#login').click(function () {
var email = $("#email").val();
var pass = $("#pass").val();
var dataString = 'email=' + email + '&pass=' + pass;
if ($.trim(email).length > 0 && $.trim(pass).length > 0) {
$.ajax({
type: "POST",
url: "ajaxlogin.php",
data: dataString,
cache: false,
success: function (data) {
if (data) {
$("body").load("index.php").hide().fadeIn(1500).delay(6000);
//or
window.location.href = "index.php";
}
else {
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
return false;
});
});
</script>
Form:
<div class="user_login">
<form action="" method="post">
<label>Email / Username</label>
<input type="email" Placeholder="Email-id" name="email" Required="required" id="email"/>
<br />
<label>Password</label>
<input type="password" Placeholder="Password" name="pass" Required="required" id="pass"/>
<br />
<div class="checkbox">
<input id="remember" type="checkbox" />
<label for="remember">Remember me on this computer</label>
</div>
<div class="action_btns">
<div class="one_half"><i class="fa fa-angle-double-left"></i> Back</div>
<div class="xyx"><input type="submit" value="Login" name="submitm" id="login"/></div>
<div id="error"></div>
</div>
</form>
Forgot password?
</div>
and php file is separate named as ajaxlogin.php:
include('includes/db.php');
if (isset($_POST['email']) && isset($_POST['pass'])) {
$pass = $_POST['pass'];
$email = $_POST['email'];
$query = "SELECT * FROM login WHERE email='$email' AND BINARY pass=BINARY '$pass'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
$_SESSION['user'] = $email;
}
}
Both Script and form are on same page. Output that i am currently getting is Error message Both for right and wrong Username/Password Match. But if i delete "return false;" from script it moves to header location without log in.
try this script,
$(document).ready(function()
{
$('#login').click(function()
{
var email = $("#email").val();
var pass = $("#pass").val();
if ($.trim(email).length > 0 && $.trim(pass).length > 0)
{
$.ajax({
type: "POST",
url: "ajaxlogin.php",
data: {email:email,pass:pass},
cache: false,
success: function(data) {
if (data)
{
$("body").load("index.php").hide().fadeIn(1500).delay(6000);
window.location.href = "index.php";
}
else
{
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
}
return false;
});
});
Looks like you are not returning any data from ajaxlogin.php
so the success function always takes control to else and throws you an error message on the screen.
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('');
Im having some trouble with a simple form. I can't seem to prevent the form from submiting if the fields are empty. Is there an easy way to check if the fields are empty, and then prevent the form submitting?
Here is my html form:
<form method="post" name="simpleForm" id="simpleForm" action="handler.php">
<fieldset>
<legend>Info</legend>
<p><label for="name">Name</label><br>
<input id="name" name="name" class="text" /></p>
<p><label for="email">Email</label><br>
<input id="email" name="email" class="text" /></p>
<legend>Questions</legend>
<p><label for="qs_1">Question 1</label><br>
<input id="qs_1" name="qs_1" class="text" /></p>
<p><label for="qs_2">Question 2</label><br>
<input id="qs_2" name="qs_2" class="text" /></p>
<p><label for="qs_3">Question 3</label><br>
<input id="qs_3" name="qs_3" class="text" /></p>
</fieldset>
<p><input type="submit" name="submit" value="Send" id="sub_btn" /></p>
</form>
Here is my javascript:
$("form#simpleForm").submit(function() {
var name = $('#name').attr('value');
var email = $('#email').attr('value');
var qs_1 = $('#qs_1').attr('value');
var qs_2 = $('#qs_2').attr('value');
var qs_3 = $('#qs_3').attr('value');
$.ajax({
type: "POST",
url: "handler.php",
data: "name="+ name +"& email="+ email +"& qs_1="+ qs_1 +"& qs_2="+ qs_2 +"& qs_3="+ qs_3,
success: function(){
$('form#simpleForm').hide(function(){$('div.success').fadeIn();});
}
});
return false;
});
Use e.preventDefault() to cancel the form submission. If you want to not send an AJAX call, add a condition check. Also, use .val() instead of .attr("value").
$("form#simpleForm").submit(function(ev) {
ev.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
var qs_1 = $('#qs_1').val();
var qs_2 = $('#qs_2').val();
var qs_3 = $('#qs_3').val();
//This condition will only be true if each value is not an empty string
if(name && email && qs_1 && qs_2 && qs_3){
$.ajax({
type: "POST",
url: "handler.php",
data: "name="+ name +"& email="+ email +"& qs_1="+ qs_1 +"& qs_2="+ qs_2 +"& qs_3="+ qs_3,
success: function(){
$('form#simpleForm').hide(function(){$('div.success').fadeIn();});
}
});
}
return false; //IE
});
In a general sense if you return false from the submit handler it will prevent the form being submitted in the standard (non-ajax) way, but I see you are already doing this - which you need to if you want to submit it via ajax instead or it will make the ajax call and submit normally.
So all you need for your validation is to put an if test that only makes the $.ajax() call if validation passes:
if (name != "" && etc...) {
$.ajax({ /* your existing ajax code here */ });
}
EDIT: you can also test that there are no blank fields with a single jQuery selector:
if ($("#simpleform :text[value='']").length === 0) {
$.ajax({ /* your existing ajax code here */ });
}
Just have an if check before making ajax request:
if(name != '' && email != '' ...)
{
//send request is true
$.ajax({
type: "POST",
url: "handler.php",
data: "name="+ name +"& email="+ email +"& qs_1="+ qs_1 +"& qs_2="+ qs_2 +"& qs_3="+ qs_3,
success: function(){
$('form#simpleForm').hide(function(){$('div.success').fadeIn();});
}
});
}
else{
return false;
}
Here is a very simple function to make a form invalid if any of the inputs is empty:
function validateForm(data){
var is_valid = true;
$.each(data, function(id, obj) {
if(obj.value === "") {
is_valid = false;
}
});
return is_valid;
}
The data argument should be a json serialized form.
Usage:
var form_data = $( "#my_form" ).serializeArray();
var is_valid = validateForm(form_data);
if(is_valid === true){
// your ajax code
}