I have form which has some inputs. I would like to show loading gif while submitting the form and hide when form is submitted.
I sent details using php and once submitted it shows response, but when submitting form, I would like to show gif as loading screen and hide when it is completed.
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#subject').val('');
$('#message').val('');
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="ajax-contact" method="post" action="mailer.php" class="mu-contact-form">
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" id="name" name="name" value="Sagar Rawal" required>
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Enter Email" id="email" value="searchbbc1881#gmail.com" name="email" required>
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Message" id="message" name="message" required>This is message </textarea>
</div>
<button type="submit" name="submit" class="mu-send-msg-btn"><span>SUBMIT</span></button>
</form>
Okay, first of all you could use modal and add gif file on top of it. Or you can simply add the image where you want to add. Here, I will work with modal.
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
var result = $.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
});
// Here, you have to add, what you want to do right after data is sent.
$("#modal").css("display", "flex");
// Overflow of main body to hidden
$("body").css("overflow", "hidden");
result.done(function(response) {
// Now, you can hide modal or loading gif
$("#modal").css("display", "none");
// Overflow of main body to hidden
$("body").css("overflow", "auto");
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Reset form at once instead
$("#ajax-contact").reset();
});
});
});
#modal {
display: none;
position: absolute;
top: 0px;
left: 0px;
height: 100%;
width: 100%;
background-color: rgba(0, 0, 0, 0.6);
justify-content: center;
align-items: center;
overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="ajax-contact" method="post" action="mailer.php" class="mu-contact-form">
<div class="form-group">
<input type="text" class="form-control" placeholder="Name" id="name" name="name" value="Sagar Rawal" required>
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Enter Email" id="email" value="searchbbc1881#gmail.com" name="email" required>
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Message" id="message" name="message" required>This is message </textarea>
</div>
<button type="submit" name="submit" class="mu-send-msg-btn"><span>SUBMIT</span></button>
</form>
<!-- My modal for modal -->
<div id="modal">
<img width=200 src="https://thumbs.gfycat.com/BogusEmptyBrontosaurus-small.gif" alt="Loading-gif"/>
</div>
In js, I have added result as object of ajax. And, right after data are sent, we show our gif file. And, after we gave got data, we will again hide gif div. Feel free to ask!!!!!!!!
Related
I've a contact form that sends data to a PHP script via AJAX. It's pretty basic but I can't get input values with serialize. The form id is correct, i obtain the input name but not their values. Here's my code. Thanks !
//Contact form AJAX
var form = $('#contact-form');
var formMessages = $('#form-messages');
// Serialize the form data.
var formData = $(form).serialize();
console.log($(form).serialize());
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).hide().fadeIn();
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#form_name').val('');
$('#form_email').val('');
$('#form_message').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).hide().fadeIn();
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text("Something went wrong.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="contact-form" class="col-md-12" method="post">
<h1>Contact</h1>
<fieldset class="form-group">
<input type="text" id="form_name" name="form_name" class="form-control" placeholder="Your name">
</fieldset>
<fieldset class="form-group">
<input type="email" id="form_email" name="form_email" class="form-control" placeholder="Your email" required>
</fieldset>
<fieldset class="form-group">
<textarea class="form-control" id="form_message" name="form_message" rows="3" placeholder="Your message" required></textarea>
</fieldset>
<button type="submit" class="btn btn-primary">Send</button>
</form>
https://jsfiddle.net/huja5pru/2/
Use serialize() method when form is submit.
check this fiddle https://jsfiddle.net/6o6htoh1/1/
You have a syntax mistake when you use the jquery selector to a jquery object, when you select your form you must use it lately like this:
var form = $('#contact-form'); //and then use it directly in the ajax call like this
form.serialize(); // not $(form).serialize()
Here is your fiddle updated https://jsfiddle.net/ingemi/kbpnmptw/ you must use serialize directly in the ajax call
I have a form and want to send the form data to a PHP file using Ajax:
This is my form:
<div class="acc_content clearfix">
<form name="contactForm" id="contactForm" class="nobottommargin" action="guarda_pass.php" method="post" >
<div class="col_full" style="color: #898989">
<label style="color: #898989" for="login-form-username">Escribe tu nueva contraseƱa:</label>
<input type="text" id="password" name="password" value="" class="form-control" required />
</div>
<div class="col_full" style="color: #898989">
<label style="color: #898989" for="login-form-username">Confirma tu nueva contraseƱa:</label>
<input type="text" id="con_password" name="con_password" value="" class="form-control" required/>
</div>
<div class="col_full nobottommargin">
<button class="button button-3d button-black nomargin" style="background-color: #6fb6e5" type= "submit" value="login">Registrar</button>
</div>
</form>
<div id="contactResponse"></div>
</div>
And this is the script:
<script src="js/jquery.js"></script>
<script>
$("#contactForm").submit(function(event)
{
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
$submit = $form.find( 'button[type="submit"]' ),
password_value = $form.find( 'input[name="password"]' ).val(),
con_password_value = $form.find( 'input[name="con_password"]' ).val(),
url = $form.attr('action');
/* Send the data using post */
var posting = $.post( url, {
password: password_value,
con_password: con_password_value
});
posting.done(function( data )
{
/* Put the results in a div */
$( "#contactResponse" ).html(data);
/* Change the button text. */
$submit.text('Sent, Thank you');
/* Disable the button. */
$submit.attr("disabled", true);
});
});
</script>
After clicking the submit button, the page reloads itself and the script is not executed.
What am I doing wrong?
Your code seems to work.
This jsfiddle shows it (I have commented out the $.post ajax call and added an alert to demonstrate this).
Maybe you included the script in a place where it is not executed or maybe it gets executed too early -- before the DOM becomes available.
You can circumvent the latter by wrapping your script into:
$(function() {
// your script content with $("#contactForm")... here
});
See .ready() on api.jquery.com for more details about this.
I am trying to have my all my text/email input forms have a required attribute before you can "Submit" The email
But since I am using some Ajax to keep the page from refreshing after pressing the button the required attribute will not work.
This is why I am asking for an alternative for required with Javascript or jQuery (trying to prevent email form spam).
HTML (FORM)
<form id="contact">
<div class="form-group">
<label for="name">Voornaam*</label>
<input name="fn" type="text" class="form-control" id="fn" required>
</div>
<div class="form-group">
<label for="name">Achternaam*</label>
<input name="ln" type="text" class="form-control" id="ln" required>
</div>
<div class="form-group">
<label for="email">Email-address*</label>
<input name="email" type="email" class="form-control" id="email" required>
</div>
<div class="form-group">
<label for="message">Bericht*</label>
<textarea name="message" required class="form-control" id="message" rows="6"></textarea>
</div>
<button type="button" onClick="doIets(); this.form.reset();"
name="submit" id="submit" class="btn btn-primary">Verstuur <span id="result"></span></button>
<div id="result2"></div>
</form>
Ajax script
<script type="text/javascript">
function doIets()
{
console.log("doe iets");
var data = {
ck: (new Date()).getTime(),
fn: $("#fn").val(),
ln: $("#ln").val(),
email: $("#email").val(),
message: $("#message").val()
};
$.ajax({
type: "POST",
url: "sendmail.php",/*php file path*/
data: data,
beforeSend: function(){
$('#result').html('<img src="loader" style="height:10px;"/>')
},
success: function(data){
$('#result').hide();
$('#result2').html(data);
}
});
}
</script>
You will need to use e.preventDefault() when they click on the submit button and then validate the form and after that submit it using the ajax call you created above.
since you already read out the data, you can check whether your message is long enough for you via
data.message.length
if it is 0 (or lower than a threshold you defined), you can skip the ajax call and return some info to the user.
You might also want to trim the message first in order to be sure there aren't only whitespace in there.
Here is part from my code, where I bind the submit event to my form and check by looping if any required field is empty or if I want to do any such thing.
This way may help you--
$('.form .contact-form').submit(function(e) {
e.preventDefault();
$('.form .message').eq(0).html("<i>Sending... Please Wait...</i>");
var form = $(this);
var validated = true;
$('input[type="text"]',this).each(function(){
if($(this).val().length < 1){
$(this).addClass('error').focus();
validated = false;
return false;
}
});
if(validated === true){
$.post(__asyn.ajaxurl, $('.form form').eq(0).serialize(), function(data, textStatus, xhr) {
console.log(data);
});
}
});
Just pass the event object to your handler onClick="doIets(event);
and then add
function doIets(event) {
event.preventDefault();
...
}
I'm trying to submit a form via jquery so that the whole page won't reloads. I'm following the instruction on jQuery.post() guide but so far it's not working. Here's what I'm looking for to complete this task.
Submit the form to a ColdFusion proxy page and from their it will send the data as json via CFHTTP.
During the process of submitting the form, show a progress gif or status.
Somehow, hide or remove the form off of the page.
Show a success or thank you message on the page where the form used to be.
So far the form I have did not even find the values from the input. The error says that "TypeError: $form.find(...).value is not a function". Below is my JavaScript code thus far:
$(function(){
$("##frmComment##").submit(function(event){
event.preventDefault();
$("##submitResponse").append('<img src="http://st2.india.com/wp-content/uploads/2014/07/ajax-loader.gif" class="progressGif">');
// Cache $form, we'll use that selector more than once
var $form=$(this);
var data = $form.serialize(); //get all the data of form
//post it
$.post(
"/customcf/knowledgeOwl/proxyPost-KB.cfm",
data,
//console.log(response),
function(response){
// Success callback. Remove your progress gif, eg:
//$('body').removeClass('in-progress');
console.log(response);
// Remove the spining gif from the div
$("##submitResponse img:last-child").remove();
//Remove the feedback form
$("##frmComment").remove();
$form.fadeOut('slow', function(){
//Add response text to the div
$("##submitResponse").append("<h6>Thank you for your feedback.</h6>");
$("##submitResponse").html(response).fadeIn('slow');
});
});
});
})
Here's the project I've setup in JSFiddle. And here's the form.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<form data-abide id="frmComment">
<div class="row">
<div class="large-12 medium-12 columns">
<div class="row" data-equalizer>
<div class="large-4 medium-4 columns">
<div class="row">
<div class="large-12 columns">
<label>
<input type="text" placeholder="Name" name="name" required>
</label>
<small class="error">Name is required and must be a string.</small>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>
<input type="text" placeholder="Email" name="mailfrom" required pattern='.*#.*\..{3}|.*#.*\..{2}'>
</label>
<small class="error">An email address is required.</small>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<div class="g-recaptcha" data-sitekey="6LfjNwITABCDPbDHdC5wx6HXRmXtqO3pgUItl-E"></div>
<noscript>
<div style="width: auto; height: 462px;">
<div style="width: auto; height: 422px; position: relative;">
<div style="width: auto; height: 422px; position: absolute;">
<iframe src="https://www.google.com/recaptcha/api/fallback?k=6LfjNwITABCDPbDHdC5wx6HXRmXtqO3pgUItl-E" frameborder="0" scrolling="no" >
</iframe>
</div>
</div>
<div style="border-style: none; bottom: 12px; left: 25px; margin: 0px; padding: 0px; right: 25px; background: ##f9f9f9; border: 1px solid ##c1c1c1; border-radius: 3px; height: 100px; width: 300px;">
<textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 280px; height: 80px; border: 1px solid ##c1c1c1; margin: 10px; padding: 0px; resize: none;"></textarea>
</div>
</div>
<br /><br />
</noscript>
</div>
</div>
</div>
<div class="large-8 medium-8 columns">
<div class="row">
<div class="large-12 columns">
<textarea id="message" name="message" placeholder="Leave a comment...we love feedback!" rows="5" required></textarea>
</div>
</div>
<div class="row">
<div class="large-12 columns">
<button type="submit" class="tiny right button">Submit</button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<div id="submitResponse"></div>
Okay, with some help, I managed to get the jQuery post to send the data to my proxyPost-KB.cfm page but it error out (505) when it hits that page. This is what I have in my proxyPost-KB.cfm page. None of the logs I setup in this CFM page is even get executed either.
<!---
Make the proxy HTTP request using. When we do this, try to pass along all of the CGI information that was made by the original AJAX request.
--->
<cflog text="CGI: #cgi#" type="Information" file="CGIparameters">
<cfhttp url="https://app.kb.com/api/head/comment.json" method="post" timeout="15" throwonerror="true">
<!---<cfhttpparam type="body" name="data"value="#serializeJSON(jsonString)#" />--->
<cfhttpparam type="url" name="_authbykey" value="56ec1f1232131c78636142d6">
<cfhttpparam type="url" name="project_id" value="55c4ffd123131c527e294fe6">
<!---<cfhttpparam type="url" name="article_id" value="#artID#">
<cfhttpparam type="url" name="content" value="#form.message#"/>
<cfhttpparam type="url" name="public_name" value="#form.name#"/>
<cfhttpparam type="url" name="public_email" value="#form.mailfrom#"/>--->
<cfhttpparam type="url" name="status" value="pending"/>
<!--- Pass along any URL values. --->
<cfloop item="strKey" collection="#URL#">
<!---<cfhttpparam type="url" name="public_name" value="#URL[strKey]#" />
<cfhttpparam type="url" name="public_email" value="#URL[strKey]#" />--->
<cflog text="URL: #URL[strKey]#" type="Information" file="CGIparameters">
</cfloop>
</cfhttp>
<!---
Get the content as a byte array (by converting it to binary,
we can echo back the appropriate length as well as use it in
the binary response stream.
--->
<cfset binResponse = ToBinary(ToBase64( objRequest.FileContent )) />
<!--- Echo back the response code. --->
<cfheader statuscode="#Val( objRequest.StatusCode )#" statustext="#ListRest( objRequest.StatusCode, ' ' )#" />
<!--- Echo back response legnth. --->
<cfheader name="content-length" value="#ArrayLen( binResponse )#" />
<!--- Echo back all response heaers. --->
<!---<cfloop item="strKey" collection="#objRequest.ResponseHeader#">
<!--- Check to see if this header is a simple value. --->
<cfif IsSimpleValue( objRequest.ResponseHeader[ strKey ] )>
<!--- Echo back header value. The cfheader tag generate the error "Complex object types cannot be converted to simple values"--->
<cfheader name="#strKey#" value="#objRequest.ResponseHeader[ strKey ]#" />
<cflog text="IsSimpleValue: #strKey#" type="Information" file="debugCFLoop">
</cfif>
</cfloop>--->--->
<!---
Echo back content with the appropriate mime type. By using
the Variable attribute, we will make sure that the content
stream is reset and ONLY the given response will be returned.
--->
<cfcontent type="#objRequest.MimeType#" variable="#binResponse#" />
Here's an example to do what you describe:
$("#frmComment").submit(function(event) {
event.preventDefault();
// Form has been submitted - now show your progress gif, eg:
// $('body').addClass('in-progress');
// or maybe:
// $('.spinner').show();
// etc - CSS can be whatever you want
// Cache $form, we'll use that selector more than once
var $form=$(this);
// Serialize all input from the form
var data=$form.serialize();
// Post it
$.post(
"your-proxy-url",
data,
function(response) {
// Success callback. Remove your progress gif, eg:
// $('body').removeClass('in-progress');
console.log(response); // show the proxy response on your console
// Now hide the form
$form.fadeOut('slow', function() {
// And show a result once it's gone
$(".result").html(response).fadeIn('slow');
});
}
);
});
I think you could use this code inside the $( "#frmComment" ).submit(function( event ) { function:
event.preventDefault();
var data = $('#frmComment').serialize(); //get all the data of form
var url = "yourUrl.php";
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
The PHP 'yourUrl' will recive the form inputs (you could use var_dump($_POST); to see the structure.
I'm trying to show a loader.gif image when my form is submited.
My loader.gif has display:none in CSS, and I want to display it, when the form is submited.
I'm trying to do this using my simple code below.
It seems correct for me but it's not working.
Do you see something wrong here?
jQuery:
$(function(){
$('form').submit(function(){
$('.loginbox h1 img').fadeIn('fast');
});
});
CSS:
.loginform h1 img {
float:right;
margin:7px 0;
display:none;
}
HTML:
<h1>Login Form: <img src="img/loader.gif"/></h1>
<form name="login" action="" method="post">
<label>
<span>User:</span>
<input type="text" name="user" />
</label>
<div class="label">
<span>Pass:</span>
<input type="password" name="pass" />
<input type="submit" value="Login"/>
</div>
</form>
I suppose that is because, once it is submitted, it is posting back or reloading or redirecting.
You can do this:
$(function(){
$('form').submit(function(e){
e.preventDefault(); // prevents submission
$('h1 img').fadeIn('fast'); // since you aren't using that class
$.ajax({ ... }); // use ajax to submit the form
});
});