Ajax form required select and input fields - javascript

im new at this so i couldnt work this out with required fields on script.
html form
<form name="rezform" onsubmit="return validation()" id="loginForm" method="" action="" novalidate="novalidate">
javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function insertData() {
var rez_ad = $("#rez_ad").val();
var rez_saat = $("#rez_saat").val();
var rez_gsm = $("#rez_gsm").val();
var rez_tarih = $("#rez_tarih").val();
var rez_email = $("#rez_email").val();
var rez_tip = $("select#rez_tip").val();
var rez_sayi = $("select#rez_sayi").val();
var rez_aciklama = $("#rez_aciklama").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "rez/insert-data.php",
data: {
rez_ad: rez_ad,
rez_saat: rez_saat,
rez_gsm: rez_gsm,
rez_email: rez_email,
rez_tarih: rez_tarih,
rez_tip: rez_tip,
rez_sayi: rez_sayi,
rez_aciklama: rez_aciklama
},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("#message").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
insert-data.php
/*
Developer: Ehtesham Mehmood
Site: PHPCodify.com
Script: Insert Data in PHP using jQuery AJAX without Page Refresh
File: Insert-Data.php
*/
include('db.php');
$rez_ad=$_POST['rez_ad'];
$rez_saat=$_POST['rez_saat'];
$rez_gsm=$_POST['rez_gsm'];
$rez_email=$_POST['rez_email'];
$rez_tarih=$_POST['rez_tarih'];
$rez_tip=$_POST['rez_tip'];
$rez_sayi=$_POST['rez_sayi'];
$rez_aciklama=$_POST['rez_aciklama'];
$stmt = $DBcon->prepare("INSERT INTO rezervasyon(rez_ad,rez_saat,rez_gsm,rez_email,rez_tarih,rez_tip,rez_sayi,rez_aciklama) VALUES(:rez_ad, :rez_saat,:rez_gsm,:rez_email,:rez_tarih,:rez_tip,:rez_sayi,:rez_aciklama)");
$stmt->bindparam(':rez_ad', $rez_ad);
$stmt->bindparam(':rez_saat', $rez_saat);
$stmt->bindparam(':rez_gsm', $rez_gsm);
$stmt->bindparam(':rez_email', $rez_email);
$stmt->bindparam(':rez_tarih', $rez_tarih);
$stmt->bindparam(':rez_tip', $rez_tip);
$stmt->bindparam(':rez_sayi', $rez_sayi);
$stmt->bindparam(':rez_aciklama', $rez_aciklama);
if($stmt->execute())
{
$res="Rezervasyonunuz tarafımıza ulaşmıştır. En yakın sürede girmiş olduğunuz GSM numaranıza dönüş yapılacaktır.";
echo json_encode($res);
}
else {
$error="Sistemsel bir hata meydana geldi lütfen bir süre sonra tekrar deneyiniz veya iletişime geçiniz.";
echo json_encode($error);
}
?>
So my problem is when i click my send button on html/php data is going mysql even if the inputs and select boxes are empty/not selected. So I have to do it required like in html input or select box. I dont know how to do it properly in javascript. I have found another script but couldnt work it same as like this one. So how can i put required field on this one and if you can explain it the logic it would be nice !
Also do we have a trick for bot protection on javascript form ?
Thanks !
And have a nice day.

You can do something like create a validation function for check whether input fields are empty or not.
function validation() {
submit = true;
var rez_ad = $("#rez_ad").val();
if ( rez_ad.trim() == "" ) {
//Do what ever you like with when empty submission.
alert('Input is empty.');
submit = false;
}
return submit;
}
Then in form on submit return this function.
<form action="" onsubmit="return validation()" method="POST">

function insertData() {
var rez_ad=$("#rez_ad").val();
var rez_saat=$("#rez_saat").val();
var rez_gsm=$("#rez_gsm").val();
var rez_tarih=$("#rez_tarih").val();
var rez_email=$("#rez_email").val();
var rez_tip=$("select#rez_tip").val();
var rez_sayi=$("select#rez_sayi").val();
var rez_aciklama=$("#rez_aciklama").val();
if(rez_ad == "" || rez_saat == "" || rez_gsm == "" || rez_tarih == "" || rez_email == "" || rez_tip == "" || rez_sayi == "" || rez_aciklama == "" ){
$("#message").html("some field is empty!!");
}else{
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "rez/insert-data.php",
data: {rez_ad:rez_ad,rez_saat:rez_saat,rez_gsm:rez_gsm,rez_email:rez_email,rez_tarih:rez_tarih,rez_tip:rez_tip,rez_sayi:rez_sayi,rez_aciklama:rez_aciklama},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("#message").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
}
<form name="rezform" onsubmit="return validation()" id="loginForm" method="POST" action="#" >

Since you are using jquery, use $('form').submit() method to return false if the validation is not success. other wise return true.
$( "form" ).submit(function( event ) {
if ( $( "input:first" ).val() === "correct" ) {
$( "span" ).text( "Validated..." ).show();
return;
}
$( "span" ).text( "Not valid!" ).show().fadeOut( 1000 );
event.preventDefault();
});
I have created a jsbin page for the reference given by jquery: https://jsbin.com/dokabod/1/edit?html,output

#alex also post the samething. I just corrected some of the errors he had. like return submit. below code working perfectly.
<form action="index.php" onsubmit="return insertData()" method="POST">
<input type="text" name="name" id="rez_ad">
<input type="text" name="name" id="rez_saat">
<input type="text" name="name" id="rez_gsm">
<input type="text" name="name" id="rez_tarih">
<input type="text" name="name" id="rez_email">
<input type="text" name="name" id="rez_tip">
<input type="text" name="name" id="rez_sayi">
<input type="text" name="name" id="rez_aciklama">
<input type="submit" name="" value="Send">
</form>
<div id="message"></div>
function insertData() {
submit = true;
var rez_ad=$("#rez_ad").val();
var rez_saat=$("#rez_saat").val();
var rez_gsm=$("#rez_gsm").val();
var rez_tarih=$("#rez_tarih").val();
var rez_email=$("#rez_email").val();
var rez_tip=$("#rez_tip").val();
var rez_sayi=$("#rez_sayi").val();
var rez_aciklama=$("#rez_aciklama").val();
if(rez_ad == "" || rez_saat == "" || rez_gsm == "" || rez_tarih == "" || rez_email == "" || rez_tip == "" || rez_sayi == "" || rez_aciklama == "" ){
$("#message").html("some field is empty!!");
submit = false;
return submit;
}else{
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "rez/insert-data.php",
data: {rez_ad:rez_ad,rez_saat:rez_saat,rez_gsm:rez_gsm,rez_email:rez_email,rez_tarih:rez_tarih,rez_tip:rez_tip,rez_sayi:rez_sayi,rez_aciklama:rez_aciklama},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("#message").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
}

Related

Kindly Resolve the Issue in My AJAX Script For Contact Form [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to achieve some AJAX Script By Which My Contact US Form Submit without Refreshing the Page
I have tried alot because i dont know where the mistake is in my AJAX Code.
This is my index.php File
<div id="response_result">
</div>
<form class="contact-form" method="POST" action="" onsubmit="return foo();" name="form" id="form_id">
<input type="text" name="contact_name" id="contact_name_id" />
<input type="text" name="contact_email" id="contact_email_id" />
<input type="text" id="contact_phone_id" name="contact_phone" />
<input type="text" id="contact_company_name_id" name="contact_company_name"/>
<input type="text" name="contact_subject" id="contact_subject_id"/>
<textarea name="contact_message" id="contact_message_id"></textarea>
<input type="submit" name="contact_submit" value="Submit Message" id="contact_submit_id" />
</form>
This is my PHP Code For That File
<?php
if(isset($_POST['contact_submit']))
{
$contact_name = $_POST['contact_name'];
$contact_email = $_POST['contact_email'];
$contact_phone = $_POST['contact_phone'];
$contact_company_name = $_POST['contact_company_name'];
$contact_subject = $_POST['contact_subject'];
$contact_message = $_POST['contact_message'];
if ((strlen($contact_message) < 5) OR (strlen($contact_message) > 500))
{
?>
<script>
alert('Your Message Should contains Characters between 5 to 500 ..... !!');
</script>
<?php
return false;
}
else if(($contact_name == "") OR ($contact_email == "") OR ($contact_phone == "") OR ($contact_company_name == "") OR ($contact_subject == "") OR ($contact_message == ""))
{
?>
<script>
alert('Please Supply Each Field .... !!');
</script>
<?php
}
else if($Object->save_contact_us_form_data($contact_name, $contact_email,$contact_phone, $contact_company_name, $contact_subject, $contact_message, $contact_date))
{
?>
<script>
alert('Data Submitted Successfully .... !!\nWe will get Back You Soon .... !!');
</script>
<?php
return true;
}
else
{
?>
<script>
alert('An Error Occured While Submitting Data .... !!');
</script>
<?php
return false;
}
}
?>
My PHP Code is Working Perfectly.
This is my AJAX Code (Not Working)
<script>
function foo()
{
var contact_name1 = document.getElementById( "contact_name_id" ).value;
var contact_email1 = document.getElementById( "contact_email_id" ).value;
var contact_phone1 = document.getElementById( "contact_phone_id" ).value;
var contact_company_name1 = document.getElementById( "contact_company_name_id" ).value;
var contact_subject1 = document.getElementById( "contact_subject_id" ).value;
var contact_message1 = document.getElementById( "contact_message_id" ).value;
$.ajax({
type: 'post',
url: 'Contact_Us.php',
data: {
contact_name:contact_name1,
contact_email:contact_email1,
contact_phone:contact_phone1,
contact_company_name:contact_company_name1,
contact_subject:contact_subject1,
contact_message:contact_message1
},
success: function (response) {
document.getElementById( "response_result" ).innerHTML = response;
}
});
}
</script>
When you submit your form with AJAX, make sure to suppress the default form submission logic using preventDefault. So your code should change to:
<form class="contact-form" method="POST" action="" name="form" id="form_id">
<input type="text" name="contact_name" id="contact_name_id" />
<input type="text" name="contact_email" id="contact_email_id" />
<input type="text" id="contact_phone_id" name="contact_phone" />
<input type="text" id="contact_company_name_id" name="contact_company_name"/>
<input type="text" name="contact_subject" id="contact_subject_id"/>
<textarea name="contact_message" id="contact_message_id"></textarea>
<input type="submit" name="contact_submit" value="Submit Message" id="contact_submit_id" />
</form>
<script>
$("#form_id").on("submit", function(e) {
e.preventDefault();
var contact_name1 = document.getElementById( "contact_name_id" ).value;
var contact_email1 = document.getElementById( "contact_email_id" ).value;
var contact_phone1 = document.getElementById( "contact_phone_id" ).value;
var contact_company_name1 = document.getElementById( "contact_company_name_id" ).value;
var contact_subject1 = document.getElementById( "contact_subject_id" ).value;
var contact_message1 = document.getElementById( "contact_message_id" ).value;
$.ajax({
type: 'post',
url: 'Contact_Us.php',
dataType: 'json',
data: {
contact_name:contact_name1,
contact_email:contact_email1,
contact_phone:contact_phone1,
contact_company_name:contact_company_name1,
contact_subject:contact_subject1,
contact_message:contact_message1,
contact_submit:"Submitted"
},
success: function (response) {
document.getElementById( "response_result" ).innerHTML = response;
}
});
});
</script>
I have added dataType to get the result as JSON. So let you PHP send JSON. (Note: Javascript alert won't work with AJAX). Hence your PHP code is:
<?php
$err = [];
if(isset($_POST['contact_submit']))
{
$contact_name = $_POST['contact_name'];
$contact_email = $_POST['contact_email'];
$contact_phone = $_POST['contact_phone'];
$contact_company_name = $_POST['contact_company_name'];
$contact_subject = $_POST['contact_subject'];
$contact_message = $_POST['contact_message'];
if ((strlen($contact_message) < 5) OR (strlen($contact_message) > 500))
{
$err[] = 'Your Message Should contains Characters between 5 to 500 ..... !!';
}
else if(($contact_name == "") OR ($contact_email == "") OR ($contact_phone == "") OR ($contact_company_name == "") OR ($contact_subject == "") OR ($contact_message == ""))
{
$err[] = "Please Supply Each Field .... !!";
}
else if($Object->save_contact_us_form_data($contact_name, $contact_email,$contact_phone, $contact_company_name, $contact_subject, $contact_message, $contact_date))
{
$err[] = 'Data Submitted Successfully .... !!\nWe will get Back You Soon .... !!';
}
else
{
$err[] = 'An Error Occured While Submitting Data .... !!';
}
echo json_encode($err);
}

Form Validation laravel

Alright , I made a form with a validation , okay , when I want to connect the validation in laravel I use this way
this is pages controller
public function getContact(){
self::$data['title'] = 'Contact us';
return view('content.contact',self::$data);
}
public function postContact(test $request){
}
}
this is the routes :
Route::get('contact','PagesController#getContact');
Route::post('contact', 'PagesController#postContact');
and this is the form
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript" href="{{asset('js/class.FormValidation.js')}}"></script>
<script type="text/javascript" href="{{asset('js/landin_validation.js')}}"></script>
<link rel="stylesheet" type="text/css" href="{{asset ('js/style.css')}}"/>
</head>
<body>
<form action="" method="post" class="landing-form">
{!! csrf_field() !!}
<label>Fill your details here - </label><br/><br/>
<input placeholder="Full name:" type="text" name="name" class="field-name" />
<input placeholder="Email:" type="text" name="email" class="field-email" />
<input placeholder="Phone Number:" type="text" name="phone" class="field-phone" />
<input type="submit" name="submit" value="Send" />
Okay so , I tried a lot to connect the validation with the form , but since it's laravel so I know the requests way but I tried a lot to connect it with this validation but doesnt work ,
this is landin_validation.js
var formValidate = new FormValidation();
$(document).ready(function () {
$('form.landing-form').submit(function () {
// Collect client info from fields
var name = $.trim( $('input[type="text"].field-name').val() );
var email = $.trim( $('input[type="text"].field-email').val() );
var phone = $.trim( $('input[type="text"].field-phone').val() );
// Reset input fields error class
$('input[type="text"]').removeClass('error');
// Form validation
if (!formValidate.testName(name) ) {
$('input[type="text"].field-name').addClass('error');
$('input[type="text"].field-name').val('');
$('input[type="text"].field-name').attr('placeholder', '* Valid full name is required!');
} else if ( !formValidate.testEmail(email) ) {
$('input[type="text"].field-email').addClass('error');
$('input[type="text"].field-email').val('');
$('input[type="text"].field-email').attr('placeholder', '* Valid email is required!');
} else if ( !formValidate.testPhone(phone) ) {
$('input[type="text"].field-phone').addClass('error');
$('input[type="text"].field-phone').val('');
$('input[type="text"].field-phone').attr('placeholder', '* Valid phone is required!');
} else {
// Open ajax call to save client details + send mail to customer
$.ajax({
url: "form_handler.php",
type: "POST",
dataType: "html",
async: "false",
data: {name: name, email: email, phone: phone},
beforeSend: function () {
var messege = '<img src="ajax-loader.gif" border="0">';
messege += ' Sending... ';
$('form.landing-form label').html(messege);
},
success: function (response) {
if (response == true) {
setTimeout(function(){
$('div.form-wrapper').html('<label>Your details has been send!</label>');
}, 2000);
} else {
$('div.form-wrapper').html('<label>Something went wrong, please try again later...</label>');
}
}
});
}
// Stop form submission
return false;
});
});
And this is FormValidation.js
function FormValidation(){
this.nameReg = [
/^([a-zA-Z\s]+){2,255}$/
];
this.emailReg = [
/^[_a-z0-9-]+(.[_a-z0-9-]+)*#[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/
];
this.phoneReg = [
/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/i,
/^[0-9]{3}.[0-9]{3}.[0-9]{4}$/i,
/^\([0-9]{3}\)-[0-9]{3}-[0-9]{4}$/i,
/^[0-9]{9,10}$/i
];
this.testName = function( nameInput ){
return this.inputCheck(this.nameReg, nameInput);
};
this.testEmail = function( emailInput ){
return this.inputCheck(this.emailReg, emailInput);
};
this.testPhone = function( phoneInput ){
return this.inputCheck(this.phoneReg, phoneInput);
};
this.inputCheck = function( regArray, inputData ){
var valid = false;
$.each( regArray, function( key, val ){
if( val.test( inputData ) ){
valid = true;
}
});
return valid;
};
}
I just want to know the way to connect the form with this validation.
I think it's not good idea to validate form data with js.Аccording to me you should validate from the server-side.If you want to have good user experience you can use this javascript lib - http://t4t5.github.io/sweetalert/

How can we send json encoded data through ajax via form text input

I am fetching php json encoded data using ajax and then setting values to form input then sending it to other page . But json fetched values does not post to other page while normal input values are posting . Here's the code i am using . Your help will be highly appriciated .
`
if(isset($_POST['send_mail'])){
header('Content-Type: application/json');
$out = array('a'=>"Volvo", 'b'=>"BMW", 'c'=>"Toyota");
echo json_encode($out);
//print_r($out);
exit();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function send_mail_test(){
var txt = $("#test_txt").val();
if( txt !=""){
$.ajax({
url : "chckvar.php",
type : "POST",
//async : false,
dataType: "JSON",
data : {
send_mail : 1,
txt_val : txt
},
success : function(data){
document.getElementById('code_r').setAttribute('value', data.a);
}
});
//return false;
}
else alert("please enter some text");
//return false;
}
</script>
<form method="post" action="sub.php" name="myform" onSubmit="return send_mail_test()">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="submit" name="_mail" value="send" >
</form>`
sub.php
<?php
print_r($_POST);
?>
UPDATE
I am using onclick on button in another form and trying to change action page from there and then submitting form to that action is that possible ??
<script>
function action(){
var str = location.href;
var x = "feedback.php?page="+str;
$("#quick_query").attr("action", x);
$('#quick_query').submit();
}
</script>
<form id="myform" method="post" action="">
<input type="button" onclick="action()">
</form>
It is changing the action but doesn't submit the form ? how can i achieve it that will be of great help.
ANSWER UPADTED:
The problem with your code is that the submit event occurs even before ajax is called. The following changes have been done in your code
HTML
<form method="post" action="sub.php" name="myform" id="myform">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="button" name="_mail" value="send" onclick="return send_mail_test()" >
</form>
<br><hr><br>
<form method="post" action="xyz.php" name="anotherform" id="anotherform">
<input type="button" name="change" value="Change action of above form" onclick="changeformaction();" >
</form>
The onsubmit on the form is removed & the submit button is changed to normal button. The send_mail_test() function is called on the Send button now.
JAVASCRIPT
<script>
function send_mail_test() {
var txt = $("#test_txt").val();
if (txt != "") {
$.ajax({
url : "chckvar.php",
type : "POST",
//async : false,
dataType : "JSON",
data : {
send_mail : 1,
txt_val : txt
},
success : function(data) {
$('#code_r').val(data.a);
$('#myform').submit();
}
});
}else{
alert("please enter some text");
return false;
}
}
function changeformaction(){
$("#myform").prop('action','newaction.php');
$('#myform').submit();
}
</script>
Here a small change is made in ajax success callback , after the response is received and the value is set in the input , the form is made to submit then.
No change is needed in your ajax file.
Try this:
<script>
$(function () {
$('form[name="myform"]').on('submit', function (e) {
e.preventDefault();
var txt = $(this).find("#test_txt").val();
if (txt.length > 0) {
$.ajax({
url: "chckvar.php",
type: "POST",
//async : false,
dataType: "JSON",
data: {
send_mail: 1,
txt_val: txt
},
success: function (data) {
$('#code_r').attr('value', data.a); //$('#code_r').val(data.a);
$(this).submit()
}
});
} else alert("please enter some text");
});
});
</script>
<form method="post" action="sub.php" name="myform">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="submit" name="_mail" value="send" >
</form>

clear form values after submission ajax

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('');

Prevent form submit with ajax if form fields are empty

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
}

Categories