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('');
Related
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);
}
});
}
}
The problem I've been trying to solve for hours and hours now is following: I cannot stop the redirecting of #myform action after the data has been submitted succesfully to database. I've tried multiple methods but none seem to work. I'm in dire need of help!
The code:
Html(mainview.php):
<div id="submitAccordion">
<form id="myForm" action="userFiles.php" method="post">
Name: <input type="text" name="accordionName" /><br />
<input id="sub" type="submit" name="go" />
</form>
<span id="result"> </span>
</div>
Javascript(mainview_script.js):
$("#sub").click(function () {
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),
data, function(info) {
$("#result").html(info); } )
});
$("#myForm").submit(function () {
return false;
});
php(userFiles.php):
session_start();
require_once 'database.php';
if ( isset($_SESSION['user_id']) ) {
$sql = "INSERT INTO useraccordion (id, h3) VALUES (:id, :accordion)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $_SESSION['user_id']);
$stmt->bindParam(':accordion', $_POST['accordionName']);
if ( $stmt->execute() ) {
echo "Succesfully inserted";
} else {
echo "Sorry, there was an error";
}
}
I have tried ajax method, prevent.default etc, but none work!
Either change your input type to button
<input id="sub" type="button" name="go" value="Submit"/>
Or try this:
$("form").submit(function(e){
e.preventDefault();
});
First, move your $("#myForm").submit(... out of the click event so it is it's own thing. Then, pass in e into that function. So it would look like this...
$("#myForm").submit(function(e) {
e.preventDefault();
return false;
});
$("#sub").click(function() {
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),data, function(info) {
$("#result").html(info);
});
});
That will fix your immediate problem. My thought is... Do not even use a form for this. There is no reason to. You are posting the data via Ajax, so there is no reason to have a form that would submit. I would do something like this...
HTML...
<div id="form">
<div class="form-item">
<label for="name">Name:</label>
<input name="name" id="name" type="text" />
</div>
<button id="sub">Submit Form</button>
</div>
Javascript...
$("#sub").click(function() {
var postData = {};
//this is here to be dynamic incase you want to add more items....
$("#form").find('input').each(function() {
postData[$(this).attr('name')] = $(this).val();
});
$.ajax({
url: "YOUR URL HERE",
type: "POST",
data: postData,
success: function(msg) {
$("#result").html(msg);
}
});
});
It is sufficient to prevent deafult action on sub:
$("#sub").click(function (e) {
e.preventDefault();
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),
data, function(info) {
$("#result").html(info); } )
});
$("#myForm").submit(function (event) { event.preventDefault(); });
That should stop the submission
If you are submitting your form data via ajax or jquery then you should change your input type form 'submit' to 'button' type
<input id="sub" type="button" name="go" value="go"/>
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 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 having an infinite cycle using this jquery code, I know WHY but I dont know HOW to fix this:
<form id="submitme">
<input value="" name="n1" id="n1" type="text"/>
<input value="Send" type="button"/>
</form>
<script>
$('#submitme').bind( 'submit', function() {
$.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
if (data == "true")
$('#submitme').submit();
});
});
</script>
The jQuery.validate plugin takes care of this and I would strongly recommend you using it:
$('#submitme').validate({
rules: {
n1: {
remote: {
url: 'validate.php',
type: 'post'
}
}
}
});
But if you don't want to use it another possibility is to use a global variable, like so:
$('#submitme').submit(function() {
if (!$.formSubmitting) {
var $form = $(this);
$.post('validate.php', { value: $('#n1').val() }, function (data) {
if (data == 'true') {
// set the global variable to true so that we don't enter
// the infinite loop and directly submit the form
$.formSubmitting = true;
$form.submit();
}
});
return false;
}
return true;
});
Just a remark: the button you have placed inside the form is not a submit button so clicking it will not trigger the submit handler. You should make it a submit button:
<input value="Send" type="submit" />
I am not a jQuery expert, but in Prototype, when you write an event handler for an action and you don't stop the default action, than it will be executed after all of your callback functionality was done. So by simply flipping the if-else statement you should be able to avoid a infinite loop:
$('#submitme').bind( 'submit', function(event) {
$.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
if (data != "true")
// if validation has failed, prevent default action (submit)
event.preventDefault();
});
// if default action was not prevented it will be executed
})
I found this solution:
<form id="submitme">
<input value="" name="n1" id="n1" type="text"/>
<input value="Send" type="button"/>
</form>
<script>
$('#submitme').bind( 'submit', function() {
if ($.data( $('#submitme' ), 'validated'))
return true;
$.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
if (data == "true") {
$.data( $('#submitme'), 'validated', true );
$('#submitme').submit();
}
});
return false;
});
</script>