form inputs are empty after alert closing - javascript

<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.

Related

if validation successful hide submit button and show loading image

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

Trying to stop form from redirecting after submit (return false & prevent.default are not working!)

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"/>

How to submit data on pressing enter key (jQuery)?

I have a ajax php comment system which works fine but it submits data on pressing comment button. I want to give some fancy touch and remove comment button, means comment will be submitted on enter key.
<form method='post' name='form' action=''>
<input type='text' name='comment' id='comment' placeholder='Write a comment....' />
<input type='button' name='submit' id='submit' value='Comment'/>
</form>
<script type="text/javascript" >
$(function() {
$("#submit").click(function() {
var test = $("#comment").val();
var comment = test;
var id = '<?php echo $id ?>';
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "comment.php",
data: {comment : comment,id : id},
cache: false,
success: function(html) {
$(".coments").prepend(html);
$("#comment").val('');
}
});
}
return false;
});
});
</script>
Code above is with comment button and works fine. Now I am trying to submit comment on enter key:
<script type="text/javascript" >
$(function() {
$('#comment').keyup(function(e) {
if(e.keyCode == 13) {
var test = $("#comment").val();
var comment = test;
var id = '<?php echo $id ?>';
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "comment.php",
data: {comment : comment,id : id},
cache: false,
success: function(html) {
$(".coments").prepend(html);
$("#comment").val('');
}
});
}
return false;
}
});
});
</script>
This code does not work on pressing enter key page is refreshed no comment is submitted.
Adjust input="button" to <input type='submit' name='submit' id='submit' value='Comment'/>.
But if you don't want the submit button to appear you can still hide it with css<input type='button' name='submit' id='submit' value='Comment' style="display:none;" />
And then you do your magic to submit the form using jQuery
$(function() {
$('#comment').keyup(function(e) {
if (e.keyCode == 13) {
var test = $("#comment").val();
var comment = test;
var id = '<?php echo $id ?>';
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "comment.php",
data: {comment : comment,id : id},
cache: false,
success: function(html) {
$(".coments").prepend(html);
$("#comment").val('');
}
});
}
}
});
Since you don't want to reload the page, I suggest you change the form element to a div element. This way, you handle the requests yourself.
<div>
<input type='text' name='comment' id='comment' placeholder='Write a comment....' />
<input type='button' name='submit' id='submit' value='Comment' />
</div>
Here's a quick fiddle: https://jsfiddle.net/w2fepLak/
If you have a button type submit, then it'll automatically submit when pressing the enter key - no JS, no magic needed!
<input type='submit' name='submit' id='submit' value='Comment'/>
Submitting on enter is actually default behavior here. What you want to do is hook in to the submit event, rather than trying to catch everything that will later cause a submit event. So:
Listen for just submit on the form element, not click or keydown.
In the submit handler, call event.preventDefault() to prevent the form from submitting and reloading the page.
In code:
$("form").on("submit", function(e) {
e.preventDefault();
var test = $("#comment").val();
var comment = test;
var id = '<?php echo $id ?>';
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "comment.php",
data: {comment : comment,id : id},
cache: false,
success: function(html) {
$(".coments").prepend(html);
$("#comment").val('');
}
});
}
});
The browser will automatically submit when there is only one input[type=text] in the form and press a enter in the input.
To fix this, you can simply add another useless input[type=text] under the form like this:
<form method='post' name='form' action=''>
<input type='text' name='comment' id='comment' placeholder='Write a comment....' />
<input type="text" style="display: none;" name="nothing" value="nothing" />
<input type='button' name='submit' id='submit' value='Comment'/>
</form>
If you are okay without <form> tag. Remove it and you are good to go.

Validation message and focus dissapearing fast on jquery ajax script

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

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

Categories