Showing a gif image while form is being processed - javascript

I am working on a spring web application where I have a login page but I want to show a gif image while the form is being processed. Please anyone can guide me through the best way to achieve this.
this is the part in my HTML page with a javascript function inside.
<div class="loginbox">
<img src = "images/login2.jpg" class="avatar" >
<form id="myForm" action="login" method='POST' onsubmit="return validate();" >
<div th:if="${param.message != null}" class="alert alert-info" th:text="${param.message[0]}">message</div>
<div th:if="${param.error != null}" class="alert alert-danger" th:text="${session[SPRING_SECURITY_LAST_EXCEPTION]}">error</div>
<p>Username</p>
<input type="text" name="username" placeholder="Enter your Email">
<p> Password</p>
<input type="password" name="password" placeholder="Enter your password">
<div>
<input id="myBtn" type="submit" name="submit" value="Login">
<img id="loadingImg" src="../images/loading.gif" style="display:none;" alt="LOADING PLEASE WAIT....">
</div>
</form>
</div>
<script th:inline="javascript">
function validate() {
if (document.f.username.value == "" && document.f.password.value == "") {
alert(/*[[#{message.username} + #{message.password}]]*/);
document.f.username.focus();
return false;
}
if (document.f.username.value == "") {
alert(/*[[#{message.username}]]*/);
document.f.username.focus();
return false;
}
if (document.f.password.value == "") {
alert(/*[[#{message.password}]]*/);
document.f.password.focus();
return false;
}
}
</script>
I tried to add something in js like this function
function validateGif(){
var myForm= document.getElementById('myForm');
var loadingImg= document.getElementById('loadingImg');
myForm.style.display='none';
loadingImg.style.display='block';
setTimeout (function(){
myForm.style.display='block';
loadingImg.style.display='none';
}5000);
}
But I know it doesnt work correclty. I want to show the gif image as long as the form is submitting and if there is some validation errors to stop the gif and show the error. However the gif image should be loading all time the to the redirection after authentication.
What is the best way to go through this.
Any help is appreciated thank you!

Here is a simple example with jQuery.
$('#myForm').submit(function (event) {
// prevent the default action of the form, i.e. submitting
event.preventDefault()
if (document.f.username.value == "" && document.f.password.value == "") {
alert(/*[[#{message.username} + #{message.password}]]*/);
document.f.username.focus();
return false;
}
else if (document.f.username.value == "") {
alert(/*[[#{message.username}]]*/);
document.f.username.focus();
return false;
}
else if (document.f.password.value == "") {
alert(/*[[#{message.password}]]*/);
document.f.password.focus();
return false;
}
}
else{
// serialize your form data
var formdata = $(this).serialize();
// show image
$('#loadingImg').fadeIn();
// run ajax request
$.ajax({
method: 'POST',
type: 'POST', // if using jquery 1.9 or earlier
data: formdata,
url: 'your/form/action',
success: function (data) {
$('#loadingImg').fadeOut();
}
});
}
});

Related

Multiple file upload using jquery serialization works only at the second call

I experience a strange problem:
Form ajax call with multiple files and form values works perfect, but only on the second call. First call ends up the the success: function(result) "else" condition. Second call works perfect and sends all data to the php. So I hit the submit button once and it shows up an empty error box and I hit the submit button again and everything works perfect.
How is that possible and how to solve that?
UPDATE #1: Found workaround, but not the solution. It works when I put if (result==="") { $(".form-application").submit(); } below the success function. But thats very dirty! ... and it upload all files twice! :-(
PROBLEM SOLVED David Knipe provided the solution!! Thank you so much!!
JQUERY:
$(".form-application").submit(function(e) {
e.preventDefault();
$("#btnSubmit2").text("Please wait...");
$("#btnSubmit2").attr("disabled", true);
var files = $('#files')[0].files;
var form = $(this);
var error='';
var formData = new FormData(this);
grecaptcha.ready(function() {
grecaptcha.execute('6Le4Qb0UAAAAAHUPcsmVYIk7zc4XCsiBnf6oE-fP', {action: 'create_comment'}).then(function(token) {
$('<input>').attr({
type: 'hidden',
value: token,
name: 'token'
}).appendTo('form');
for(var count = 0; count<files.length; count++)
{
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
error += "Invalid " + count + " Image File"
}
else
{
formData.append("files[]", document.getElementById('files').files[count]);
}
}
if(error == '')
{
$.ajax({
url: form.attr("action"),
method: form.attr("method"),
data: formData,
processData: false,
contentType: false,
success: function(result) {
if (result == "0") {
$("#btnSubmit2").text("Thank you!");
$("#btnSubmit2").attr("disabled", true);
$(".output_message").text("");
$(':input','.form-application')
.not(':button, :submit, :reset, :hidden')
.val('')
.prop('checked', false)
.prop('selected', false);
$(".output_message").append("<div class='alert alert-success alert-dismissible fade show' role='alert'>We have received your application!</div>");
} else {
$(".output_message").text("");
$(".output_message").append("<div class='alert alert-danger alert-dismissible fade show' role='alert'>"+result+"</div>");
$("#btnSubmit2").attr("disabled", false);
$("#btnSubmit2").text("try again");
}
}
});
}
else
{
alert(error);
}
});
});
return false;
});
HTML:
<form class="form-application" id="applicationform" method="post" action="https://<?PHP echo $_SERVER['HTTP_HOST']; ?>/include/process-application.php" enctype="multipart/form-data">
<input type="hidden" name="crsf" value="<?=$_SESSION['crsf']?>"/>
<input type="hidden" name="crsf-expire" value="<?=$_SESSION['crsf-expire']?>"/>
<div class="space40"></div>
<h6>Name</h6>
<input name="name" type="text" class="form-control" placeholder="Your Name">
<div class="space30"></div>
<h6>Email</h6>
<input name="email" type="text" class="form-control" placeholder="Your Email Address">
<div class="space30"></div>
<h6>Instagram Name</h6>
<input name="instagram" type="text" class="form-control" placeholder="Your Instagram Name">
<div class="space30"></div>
<h6>City & Country</h6>
<input name="from" type="text" class="form-control" placeholder="Where do you live?">
<div class="space30"></div>
<h6>Tell us more about you</h6>
<textarea name="message" class="form-control" rows="3" placeholder="Write some details about you, so we know you better."></textarea>
<div class="space30"></div>
<h6>Upload some photos of yourself</h6>
<div class="file-field">
<div class="btn btn-aqua">
<input name="files" id="files" type="file" accepts="image/*" multiple>
</div>
<div class="file-path-wrapper">
</div>
<div class="space20"></div>
</div>
</div>
<div class="col-12 text-center">
<button id="btnSubmit2" type="submit" class="btn btn-full-rounded btn-aqua">Submit Application</button>
<div class="space10"></div>
<span class="output_message"></span>
</div>
</form>
PHP Script /include/process-application.php
<?PHP
echo "0";
?>
OK, I think I've figured this out. $('<input>').attr(...); sets the token attribute on a new <input> element. But this is after var formData = new FormData(this);, so the token doesn't get included in formData. Then I guess you get an authentication error, and I guess it does the authentication before it even gets to the PHP part. It would just be a HTTP401 response with no body, hence "". But then, on the second attempt, the <input> has already been created with the correct token, and this ends up being used to authenticate.
Either keep onsubmit or action. Remove action from form tag, it will work

My First Contact Form using PHP & JavaScript - No Page Redirect

Writing my first website that uses a contact form. In researching this myself so far, I came across the following article that I've been following:
http://www.nfriedly.com/techblog/2009/11/how-to-build-a-spam-free-contact-forms-without-captchas/
So far, however, it's not working. I have the contact page uploaded to a shared hosting server that has PHP on it. What follows is the code I have so far.
Here is the relevant content within the *.html file to the form:
<form action="/submit.php" method="post">
<span>Name</span>
<br>
<input id="name-text" type="text" name="name">
<br>
<span>Email</span>
<br>
<input id="email-text" type="text" name="email">
<br>
<span>Subject</span>
<br>
<input id="subject-text" type="text" name="subject">
<br>
<input id="antispam-text" type="text" name="url" style="display:none;">
<span>Message</span>
<br>
<textarea id="message-text" name="message"></textarea>
<br>
<div class="form-submit">
<input id="submit-button" class="menu" type="submit" value="Submit">
</div>
<br>
<div class="form-submit">
<span id="sent-status"></span>
</div>
</form>
Here is the relevant content within the *.css file to the form:
input[type="text"], textarea {
width: 90%;
margin: 10px;
font-size: var(--font-text4);
}
textarea {
height: 90px;
}
#submit-button:hover {
border-color: #7AC943;
}
.form-submit {
text-align: center;
margin:-20px;
}
#submit-button {
background-color: transparent;
width: 150px;
border: var(--thin-border);
color: var(--font-color);
font-size: var(--font-text3);
}
#sent-status {
margin: -10px;
padding: 7px;
visibility: hidden;
background-color: #000000;
}
Here is the relevant content within the *.js file to the form:
document.getElementById('submit-button').addEventListener('click', function () {
var formFilled = true;
if (document.getElementById('name-text').value == '')
formFilled = false;
if (document.getElementById('email-text').value == '')
formFilled = false;
if (document.getElementById('subject-text').value == '')
formFilled = false;
if (document.getElementById('message-text').value == '')
formFilled = false;
document.getElementById('sent-status').style.visibility = 'visible';
if (formFilled) {
document.getElementById('sent-status').style.color = '#7AC943';
document.getElementById('sent-status').innerText = 'Message Sent Successfully';
}
else {
document.getElementById('sent-status').style.color = '#FF1D25';
document.getElementById('sent-status').innerText = 'Contact Form Incomplete';
}
});
Here is the entire contents of the submit.php file:
<?php
// If the URL field is empty...
if(isset($_POST['url']) && $_POST['url'] == ''){
// then send the form to your email.
mail('beta#email.com', 'Contact Form', print_r($_POST,true) );
}
// Else, let the spammer think that they got their message through.
?>
Here are the following technical issues that affect this contact form:
Filling out all fields of the form and clicking the Submit button, the browser then goes to the submit.php file and leaves the *.html file. I want the browser to stay on the *.html file the whole time and never load the submit.php file as if it were a webpage.
Clicking the Submit button, then checking the target email account I specified, nothing arrives in inbox nor spam. The email account otherwise sends/receives email messages just fine. In the submit.php code, you'll see I put beta#email.com which is not the actual target email. For this post, I'm keeping my actual email target address private.
Much appreciated for the assistance.
You can use the Fetch API, first prevent the default action of the submit button then send the form information using fetch like this:
document.getElementById('submit-button').addEventListener('click', function (event) {
event.preventDefault();
var formFilled = true;
if (document.getElementById('name-text').value == '')
formFilled = false;
if (document.getElementById('email-text').value == '')
formFilled = false;
if (document.getElementById('subject-text').value == '')
formFilled = false;
if (document.getElementById('message-text').value == '')
formFilled = false;
document.getElementById('sent-status').style.visibility = 'visible';
if (formFilled) {
const form = document.querySelector('form');
const data = new FormData(form);
fetch('/submit.php', {
body: data,
cache: 'no-cache',
method: 'POST',
mode: 'cors'
})
.then(res => res.text())
.then(result => {
if (result === 'ok') {
document.getElementById('sent-status').style.color = '#7AC943';
document.getElementById('sent-status').innerText = 'Message Sent Successfully';
} else {
//failed message here ...
}
});
} else {
document.getElementById('sent-status').style.color = '#FF1D25';
document.getElementById('sent-status').innerText = 'Contact Form Incomplete';
}
});
and make this change to the submit.php file:
<?php
if(isset($_POST['url']) && $_POST['url'] == ''){
extract($_POST);
mail('beta#email.com', 'Contact Form', $message);
echo 'ok';
}
in the mail function, the third argument should be the message, extract the message from the $_POST array and feed it to the mail function
You can try by using jQuery AJAX. Here is a sample of code that can be helpful for you.
HTML
<form action="" method="post" id="myForm">
<span>Name</span>
<br>
<input id="name-text" type="text" name="name">
<br>
<span>Email</span>
<br>
<input id="email-text" type="text" name="email">
<br>
<span>Subject</span>
<br>
<input id="subject-text" type="text" name="subject">
<br>
<input id="antispam-text" type="text" name="url" style="display:none;">
<span>Message</span>
<br>
<textarea id="message-text" name="message"></textarea>
<br>
<div class="form-submit">
<input id="submit-button" class="menu" type="submit" value="Submit">
</div>
<br>
<div class="form-submit">
<span id="sent-status"></span>
</div>
</form>
Then in your js file put this code (I've skipped the validation process, but in your production code don't forget to do it!)
$(document).ready(function(){
$('#myForm').on('submit',function(event){
event.preventDefault();
var data = $(this).serialize();
$.ajax({
type: 'POST',
url: '/submit.php',
data: data,
success: function(response){
// do your code stuff here if all goes well
},
error: function(err){
// do your code stuff here in case of errors
}
});
});
});

Automatic Login

I'm trying to automatically login a user. The JavaScript code below here actually does that but only when I remove the 'login/submit' div (), and then stops working when I include the 'div'. I can't remove this 'div' as that is my submit button. I don't know how to get around this problem, any help will be appreciated.
HTML;
<body>
<form name="EventConfirmRedirection" class="Form" method="post" action="index.php" id="myForm" data-ajax="false">
<div class="user_login3"><input style="text-transform:lowercase" type="text" name="username" id="username" placeholder="username"></div>
<div class="user_login3"><input type="password" name="password" id="password" placeholder="password"></div>
<div style="margin-left:5%; width:45%; font-size:5px;">
<input data-theme="c" type="checkbox" id="rememberMe" name="rememberMe"/>
<label for="rememberMe"><span style="font-size:12px">remember me</span></label>
</div>
<div style="margin-left:5%; color:#FF0000; font-weight:bold" id="error"></div>
<div class="login"><input type="submit" value="LOGIN" name="submit" data-theme="e" id="submit"></div>
</form>
</body>
JAVASCRIPT;
$(document).ready(function() {
"use strict";
if (window.localStorage.checkBoxValidation && window.localStorage.checkBoxValidation !== '') {
$('#rememberMe').attr('checked', 'checked');
$('#username').val(window.localStorage.userName);
$('#password').val(window.localStorage.passWord);
document.EventConfirmRedirection.submit();
} else {
$('#rememberMe').removeAttr('checked');
$('#username').val('');
$('#password').val('');
}
$('#rememberMe').click(function() {
if ($('#rememberMe').is(':checked')) {
// save username and password
window.localStorage.userName = $('#username').val();
window.localStorage.passWord = $('#password').val();
window.localStorage.checkBoxValidation = $('#rememberMe').val();
} else {
window.localStorage.userName = '';
window.localStorage.passWord = '';
window.localStorage.checkBoxValidation = '';
}
});
});
AJAX
$(document).ready(function() {
"use strict";
$("#submit").click( function(e) {
e.preventDefault();
if( $("#username").val() === "" || $("#password").val() === "" )
{
$("div#error").html("Both username and password are required");
} else {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(data) {
$("div#error").html(data);
});
$("#myForm").submit( function() {
return false;
});
}
});
});
"submit is not a function" means that you named your submit button or some other element submit. Rename the button to btnSubmit and your call will magically work. Any of the form element name and id should not be submit, otherwise form.submit will refer to that element rather than submit function.
When you name the button submit, you override the submit() function on the form.
So changing the div/submit like this will work for you
<div class="login"><input type="submit" value="LOGIN" name="btnSubmit" data-theme="e" id="btnSubmit"></div>
And if you don't want to change the button name then you might call the submit function natively aswell, which looks a bit dirty..
document.EventConfirmRedirection.prototype.submit.call(document.EventConfirmRedirection);
//or
document.EventConfirmRedirection.prototype.submit.call($('#myForm')[0]);

JS/jQuery event.submit/return true not woking

I am wondering if someone can help me as i cant figure this out. I have this validation script that checks an email form for contents and valid email and it is working correctly however it is not submitting the form if everything is okay..it just removes to error messages and does nothing.
I have a strange feeling it will be something stupid but i cant see anything wrong here.
HTML
<!DOCTYPE html>
<html>
<head>
<?php include('includes/head.php'); ?>
<script type="text/javascript" src="js/contactVal.js"></script>
</head>
<body>
<?php include('includes/navbar.php'); ?>
<div class="container">
<div class="row">
<div class="col-md-8">
<h3>Contact Form</h3>
<p>Use this handy little contact form to get in contact with me about anything at all. If you have a job offer or any questions about me then feel free to drop me a message, ill get back to you as soon as possible.</p>
<hr>
<div id="form-response">
</div>
<form id="mailer" action="scripts/mailer.php" method="POST">
<h3>Name:</h3>
<input type="text" id="name" name="name" placeholder="Enter your name"></input><br />
<h3>Email:</h3>
<input type="email" id="email" name="email" placeholder="Enter your email address"></input><br />
<h3>Subject:</h3>
<input type="text" id="subject" name="subject" placeholder="Enter the subject of your message"></input><br />
<h3>Message:</h3>
<textarea id="message" name="message" placeholder="Enter your message here..."></textarea><br />
<input type="submit" name="submit" id="submit" value="Send"></input><br /><br />
<input type="hidden" name="honeypot" id="honeypot" value="http://" />
<input type="hidden" name="human" id="human" value="" />
</form>
</div>
<div class="col-md-4">
<h3>Details</h3>
<p><img class="about-arrow" src="img/icons/arrow.png" />Email: contact#alexvolley.co.uk</p>
<p><img class="about-arrow" src="img/icons/arrow.png" />Website: www.alexvolley.co.uk</p>
<p><img class="about-arrow" src="img/icons/arrow.png" />Mobile: On request</p>
<hr>
<h3>Socials</h3>
<a class="big" href="http://www.facebook.com/oukp3ngu1nx"><img class="about-arrow" src="img/icons/arrow.png" />Facebook</a><br />
<a class="big" href="http://www.twitter.com/alex_volley_"><img class="about-arrow" src="img/icons/arrow.png" />Twitter</a><br />
<a class="big" href="https://www.linkedin.com/pub/alex-volley/97/27/906"><img class="about-arrow" src="img/icons/arrow.png" />LinkedIn</a><br />
</div>
</div>
</div>
<?php include('includes/footer.php'); ?>
</body>
</html>
JAVASCRIPT
$(document).ready(function(){
$('#form-response').hide();
$('#form-response').click(function(){
$('#form-response').fadeOut();
});
$('#submit').click(function(){
event.preventDefault();
var valid = '';
var name = $('form #name').val();
var email = $('form #email').val();
var subject = $('form #subject').val();
var message = $('form #message').val();
var honey = $('form #honeypot').val();
var human = $('form #human').val();
var filter = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
//check for human interaction
if(honey == 'http://' && human == ""){
//check fields
if(name == '' || null || name.length < 2){
valid = '<p>You need to enter your name.</p>';
}
if(email == '' || null || email.length < 5){
valid += '<p>You need to enter an email address.</p>';
}
if(!email.match(filter)){
valid += '<p>You need to enter a valid email address.</p>';
}
if(subject == '' || null || subject.length < 2){
valid += '<p>You need to enter a valid subject.</p>';
}
if(message == '' || null || message.length < 30){
valid += '<p>You need to enter a message of at least 30 characters.</p>';
}
//check if valid
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
} else {
$('#form-response').fadeOut('slow');
$('#form-response').hide();
return true;
}
} else {
//spambot
error = '<p>Back of bot boy.</p>';
}
});
});
You did not pass event in the function arguments:
$('#submit').click(function( event ){
event.preventDefault();
You're probably better off using the submit event and letting the submit button do it's job:
$('#mailer').submit(function( event ){
event.preventDefault();
........
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
this.submit(); //ONCE EVERYTHING CHECKS OUT
} else {
.....
JS FIDDLE DEMO
EDIT
To resolve the error Uncaught TypeError: object is not a function, please change the name of your submit button to something else: this.submit -- the button, is conflicting with this.submit() -- the function.
Here is a version that works fine after changing: name="submit" to name="submit-button"
By the way your input elements do not need a closing tag </input>
REF: Uncaught TypeError: object is not a function, button inside form
May be you can try following code. On Submit button click validate form and if everything is fine submit form using .submit method.
$('#submit').click(function( event ){
event.preventDefault();
............
if(valid != ''){
$('#form-response').removeClass().addClass('error').html('<h3>There was a few problems..</h3>' + valid).fadeIn('slow');
} else {
$('#form-response').fadeOut('slow');
$('#form-response').hide();
$('#mailer').submit(); //ONCE EVERYTHING CHECKS OUT
}
..............

Form submit with 'return false' reloads current page

I have been trying to fix this code for hours, and I still cannot make it work.
This is rather basic:
I am building an hybrid iOS app, and there is an area which requires the user to log into our system, and I use Hammer.js to handle touch events.
So, on the page, I have a form and a submit button. And in my JS app file, there is the ajax requests to my server to check credentials.
Though, it doesn't work: my form keeps reloading the page, whatever I do. And as it refreshes the window, my ajax request doesn't get any chance to work.
Here is the HTML form:
<div class="login-form-parent">
<div class="login-form">
<section>
<h2>Sign in to GraphiX Studios CPM</h2>
<form name="loginForm" id="login" method="post" submit="#" >
<fieldset>
<input type="text" name="login" id="loginEmail" placeholder="Username" autocapitalize="false" autocorrect="false" >
<input type="password" name="password" id="loginPass" placeholder="••••" >
<aside>
<label for="rememberLogin">Remember me</label>
<input type="checkbox" name="rememberLogin" id="rememberLogin" >
</aside>
<footer>
<input type="submit" name="submit" id="submitLogin" value="Login" >
</footer>
</fieldset>
</form>
</section>
</div>
</div>
The two <div>, the <aside>, <section> and <footer> tags are only here for styling purposes.
And here is the JS code:
var loginEl = document.getElementById('submitLogin');
Hammer(loginEl, {tap_max_touchtime: 1000}).on("tap", loginFunctions);
function loginFunctions() {
var usernameValidation = $("input#loginEmail").val();
if (usernameValidation == "") {
$("#login_error").show();
$("input#login").focus();
return false;
}
var passwordValidation = $("input#loginPass").val();
if (passwordValidation == "") {
$("#password_error").show();
$("input#password").focus();
return false;
}
if (usernameValidation != "" && passwordValidation != "") {
$.submit(function() {
var username = $('#loginEmail').val();
var password = $('#loginPass').val();
$.ajax({
url: 'loginProcessing.php',
type: 'POST',
data: {
user: username,
pass: password
},
success: function(response) {
if(response == '1') {
// Success
alert('Success');
} else {
// Error
alert('Failed');
}
}
});
return false;
});
}
return false;
}
I can't debug that on my own: I've been trying for hours different solutions and I've already searched among Google and Stack Overflow resources.
Feel free to clean up or improve the JS code.
try using:
event.preventDefault();
instead of return false, in the start of your $.submit function
change <input type="submit" name="submit" id="submitLogin" value="Login" > for <input type="button" name="submit" id="submitLogin" value="Login" >

Categories

Resources