Refresh form after AJAX call - javascript

Background
I have an email sign-up form on a website.
The form appears in two areas of each web page: the header and the footer
It's the same exact form, just available on the top and bottom of the page for better UX and accessibility.
The form uses a jQuery/AJAX script to provide success and error responses to the user. (i.e., "Success! Your subscription is complete." and "Error. Please review and re-submit")
When the user submits the form, the user input is added to the database AND a notification email is sent to site admins.
If the header form is used, the email subject reads "Email Subscriber Added (Header Form)".
If the footer form is used, the subject reads "Email Subscriber Added (Footer Form)".
(This is just a simple technique to let admins gauge the usage of each form.)
Here's what the PHP looks like:
if ( $form_selected == 'header' ) {
$mail->Subject = 'Email Subscriber Added (Header Form)';
$mail->Body = $message;
} elseif ( $form_selected == 'footer' ) {
$mail->Subject = 'Email Subscriber Added (Footer Form)';
$mail->Body = $message;
} else {
$mail->Subject = 'Email Subscriber Added (form version unknown)';
$mail->Body = $message;
}
To this point, everything works fine.
The Problem
The problem is that, if the site user submits multiple email subscriptions in the same session, site admins get the else version in the PHP script above ("form version unknown"). This option should never be invoked during a normal session. But the page needs to be refreshed before the if and elseif options are considered again.
Question
Is there a way to solve this problem in the jQuery/AJAX script (see below)? I'm open to modifying the PHP, as well, if necessary.
$(function() {
// set up event listener
$('#header-form, #footer-form').submit(function(e) {
// disable html submit button
e.preventDefault();
// get the submit button
var submitButton = $('[type=submit]', this);
// get the messages element
var formResponses = $('#header-form-responses, #footer-form-responses', this);
formResponses.text(" ");
// serialize form data
var formData = $(this).serialize();
// disable submit button to prevent unnecessary submission
submitButton.attr('disabled', 'disabled');
// tell users that form is sending
submitButton.text('Processing...');
// submit form via AJAX
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData
})
.done(function(response) {
// make sure formResponses element has 'success' class
$(formResponses).removeClass('error');
$(formResponses).addClass('success');
// set message text
$(formResponses).text('Your subscription is complete. Thank you!');
// clear form
$('input').val('');
})
.fail(function(data) {
// make sure formResponses element has 'error' class
$(formResponses).removeClass('success');
$(formResponses).addClass('error');
// set the message text
$(formResponses).text('Input error. Please review and re-submit.');
})
.always(function(data) { // this will always fire even if the request fails
submitButton.removeAttr('disabled');
submitButton.text('Send');
});
});
});
<!-- simplified HTML -->
<form action="process_form.php" method="post" id="header-form">
<input type="email" name="email_subscription">
<input type="hidden" name="formtarget" value="header">
<button type="submit" name="submit_subscription">Submit (Header)</button>
<p id="header-form-responses"></p>
</form>
<form action="process_form.php" method="post" id="footer-form">
<input type="email" name="email_subscription">
<input type="hidden" name="formtarget" value="footer">
<button type="submit" name="submit_subscription">Submit (Footer)</button>
<p id="footer-form-responses"></p>
</form>

If this contains the data which triggers those PHP if conditions:
<input type="hidden" name="formtarget" value="header">
Then this is explicitly clearing that data:
// clear form
$('input').val('');
Instead, only clear the fields you want to clear:
// clear form
$('input[type="email"]').val('');

Use $('input:not([type="hidden"])').val('') to exclude the hidden input from clearing. Your JS is clearing all inputs including your hidden inputs.
$(function() {
// set up event listener
$('#header-form, #footer-form').submit(function(e) {
// disable html submit button
e.preventDefault();
// get the submit button
var submitButton = $('[type=submit]', this);
// get the messages element
var formResponses = $('#header-form-responses, #footer-form-responses', this);
formResponses.text(" ");
// serialize form data
var formData = $(this).serialize();
// disable submit button to prevent unnecessary submission
submitButton.attr('disabled', 'disabled');
// tell users that form is sending
submitButton.text('Processing...');
// submit form via AJAX
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData
})
.done(function(response) {
// make sure formResponses element has 'success' class
$(formResponses).removeClass('error');
$(formResponses).addClass('success');
// set message text
$(formResponses).text('Your subscription is complete. Thank you!');
// clear form except hidden inputs
$('input:not([type="hidden"])').val('')
})
.fail(function(data) {
// make sure formResponses element has 'error' class
$(formResponses).removeClass('success');
$(formResponses).addClass('error');
// set the message text
$(formResponses).text('Input error. Please review and re-submit.');
})
.always(function(data) { // this will always fire even if the request fails
submitButton.removeAttr('disabled');
submitButton.text('Send');
});
});
});
<!-- simplified HTML -->
<form action="process_form.php" method="post" id="header-form">
<input type="email" name="email_subscription">
<input type="hidden" name="formtarget" value="header">
<button type="submit" name="submit_subscription">Submit (Header)</button>
<p id="header-form-responses"></p>
</form>
<form action="process_form.php" method="post" id="footer-form">
<input type="email" name="email_subscription">
<input type="hidden" name="formtarget" value="footer">
<button type="submit" name="submit_subscription">Submit (Footer)</button>
<p id="footer-form-responses"></p>
</form>

Related

PHP code doesnt work together with JS function on "onclick"

i have a button in which i want it to perform 2 task; php and js.
The php part : generate different text everytime the button is pressed.
The js part : disabling the button for 5 secs and then enabling it back.
HTML
<button onclick = "disable();" class=btnGenerate type="submit" id="submit" name="submit" >GENERATE</button>
PHP
if(isset($_POST['submit'])){
$num=mt_rand(1,10);
$result=mysqli_query($con,"SELECT * from quote_table where id=$num");
$row = $result->fetch_assoc();}
JS
<script>
function disable(){
document.getElementById("submit").disabled = true;
setTimeout(function() { enable(); }, 5000); }
function enable(){
document.getElementById("submit").disabled = false;
}</script>
The PHP part only works when i delete the "onclick = "disable();" on the html but it doest seem to work when i add it. Can a button carry out PHP and JS at a single click ? Thanks in advance.
A disabled button can't be a successful control.
Don't depend on the name/value of the submit button being submitted in the form data if you are going to disable it.
Replace isset($_POST['submit']) with some other condition.
If you trigger a form submission, unless you're using AJAX the page will simply reload, rendering the enable() method moot unless
you're using it to re-enable the button on fail condition or on
successful return of data via AJAX.
It's sounds to me like you're trying to get data via request to the server, without reloading the page, and then re-enable the submit button after the data is returned. In that case you need to use AJAX.
HTML
<form action="/" method="post" id="form">
<button class=btnGenerate type="submit" id="submit" name="submit" >GENERATE</button>
</form>
JS
<script>
document.getElementById('submit').addEventListener('click', function(event){
event.preventDefault(); // prevents browser from submitting form
var form = document.getElementById('form');
var submit = document.getElementById('submit');
// using JQuery ajax
$.ajax(form.action, {
data: form.serialize(),
beforeSend: function() { // runs before ajax call made
// disable submit button
submit.disabled = true;
},
success: function(response) {
console.log(response);
// deal your return data here
},
error: function(error) {
console.log(error);
// deal with error
},
complete: function() { // runs when ajax call fully complete
// renable submit button
submit.disabled = false;
}
});
});
</script>

Form submission js/jquery staying on same page

I'm trying to submit a form inside a CMS page and don't want a new page to load after processing the php mail script. Instead I need to display a single line success message (not an alert pop up box) without reloading the page or going to a different page.
Here's the code I have and my understanding is that the event.preventDefault should allow to stay on same page and $("#contactResponse").html(data); should put the success message on the same page.
This is my div tag above the form which is supposed to receive the success message (I've tried putting it after my form too):
<div id="contactResponse"></div>
This is my form tag:
Edit: Including my form code as well: (The div class stuff is from a custom css that someone else has done)
<form id="contactForm" name="contactForm" method="post" action="/myemail.php">
<div class="form-group"><input class="form-control" name="email" type="email" placeholder="Email Address" /></div>
</div>
<div class="col-sm-4">
<div class="form-group"><input class="form-control" name="question" type="text" placeholder="What is your question?" /></div>
</div>
<div class="form-group"><input class="btn btn-warning btn-block" type="submit" value="Request Information"></div>
</form>
This is the script above my form and div tag:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$("#contactForm").submit(function(event) {
event.preventDefault();
var $form = $(this),
$submit = $form.find('button[type="submit"]'),
email_value = $form.find('input[name="email"]').val(),
message_value = $form.find('input[name="question"]').val(),
url = $form.attr('action');
var posting = $.post(url, {
email: email_value,
question: message_value
});
posting.done(function(data) {
$("#contactResponse").html(data);
});
});
</script>
The email works but the php script is on the server, and it takes me to a different page.
Can someone please give me some suggestions/advice.
Thanks
Try this, it works for me
<script>
// Get the form.
var form = $('#contactForm');
// Get the messages div.
var formMessages = $('#contactResponse');
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.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('');
// $('#company').val('');
$('#message').val('');
$(form).hide();
}).fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
$( "#contact" ).children(".loading").remove();
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
</script>

how to refresh a particular div after jquery form submission [duplicate]

This question already has answers here:
Ajax - How refresh <DIV> after submit
(5 answers)
Closed 7 years ago.
// My jquery for form submission
$(document).ready(function() {
var form = $('#form1'); // contact form
var submit = $('#submit1'); // submit button
var alert = $('.alert1'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
// sending ajax request through jQuery
$.ajax({
url: 'giftcard_check.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Checking....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.html('Apply'); // reset submit button text
},
error: function(e) {
console.log(e)
}
});
});
});
// My form
<p>
<form action="" method="post" id="form1">
<input type="text" name="valuebox" placeholder="type your code" required />
<button name="submit" class="button1" type="submit" id="submit1">Apply</button>
</form>
</p>
<div class="alert1">Hello</div>
// giftcard_check.php
include("include/dbconnection.php");
dbconnect();
session_start();
$_SESSION['fromttl'] = 0;
$valuebox = $_POST['valuebox'];
$query = "SELECT * FROM db_coupon WHERE code='$valuebox' AND publish='1'";
$result = mysql_query($query);
$length = mysql_num_rows($result);
$rows = mysql_fetch_array($result);
$discount = $rows['discount'];
if($length == 1)
{
$_SESSION['fromttl'] = $discount;
echo $_SESSION['fromttl'];
}
else
{
$_SESSION['fromttl'] = 0;
echo "Invalid Gift Card!";
}
My question is how to refresh a particular div (ie,
<div id="show"><?php echo $_SESSION['fromttl']; ?></div>
) immediate after the form submission.
My current result not refreshing the particular div after form submission. I don't want to refresh whole page, only a particular div. If i refresh whole page the div will be refreshed.
Is there any solution? I am stuck here.
You should try this, put a return false;at the end of your form.on('submit',... it will not submit your form request and you will stay on the same page :
// My jquery for form submission
$(document).ready(function() {
var form = $('#form1'); // contact form
var submit = $('#submit1'); // submit button
var alert = $('.alert1'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
// sending ajax request through jQuery
$.ajax({
url: 'giftcard_check.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Checking....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.html('Apply'); // reset submit button text
if(data != 'Invalid Gift Card!') {
$('div.show').html(data);
}
},
error: function(e) {
console.log(e)
}
});
return false; //Will not active the form submission
});
});
// My form
<p>
<form action="" method="post" id="form1">
<input type="text" name="valuebox" placeholder="type your code" required />
<button name="submit" class="button1" type="submit" id="submit1">Apply</button>
</form>
</p>
<div class="show"></div>
<div class="alert1">Hello</div>
After your form submission, you can clear the content of div as:
$("#show").html("");
Then, update the div content as you required.
empty the content of the division you want using jQuery empty()
for example if you want to clear that div after form reset then simply add
...
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
$('#show').empty(); // clear div from previous content
submit.html('Apply'); // reset submit button text
},
...
in case that "show" div needs not to be empty use html()

Form Submitting Via AJAX Despite Failing Validation

I'm new to Ajax and I wanted to use it with a contact form currently in use. The form is set up to run JS (fieldchk()) to validate the require fields and then sends an email to the appropriate party.
I have set up the Ajax correctly, in that the email is sent and a message is displayed on the same page:
$('form').on('submit', function(event) {
event.preventDefault();
return fieldchk();
var url = $(this).attr('action');
var formData = $(this).serialize();
$.post(url, formData, function(response){
$('#feedback_form').html("<p>Thanks for contacting us!</p>");
});
});
Edit: now the form gets validated and if it's valid, it does not send the email. Validation works correctly now.
Here is my form code:
<form
name="feedback"
action="feedbackact.cfm?type=feedback"
method="post"
enctype="multipart/form-data"
>
This is the code I use to validate the form:
function fieldchk() {
errmsg = '';
if (document.feedback.name.value == ''){
errmsg = errmsg + 'You must enter your name.\n';
}
... all the fields get checked like this ...
if (errmsg > ''){
alert(errmsg);
return false;
}
}
You will need to add some type of validation in your JavaScript function. I would modify the markup
<form
name="feedback"
action="feedbackact.cfm?type=feedback"
method="post"
enctype="multipart/form-data"
>
You do not need the onsubmit because the event listener is already listening for the form name. I assume the feedbackact.cfm page is what is determining if the form is valid or not? If that's the case, you're probably going to need to pass the form values to the coldfusion.
However I would do this differently:
HTML:
<form name='feedback'><!--inputs--></form>
JavaScript:
$('form[name="feedback"]').on('submit', function() {
var formData = this.serializeArray();
if ( fieldcheck( formData) ) { //verifying the form data is correct
$.post(); //post data
Coldfusion.navigate("feedbackact.cfm?type=feedback");
}
else { alert('not filled out correctly!') }
});

Disable form inputs after ajax submission

I have a form that submits via Ajax. After the user sends the form, the text changes displaying the form was sent successfully and then shows the form filled out. I want to display the form but I don't want them to re-submit the form so I want to disable the inputs as well as the submit button. I tried adding: $('#submit_btn').className +=" disabled" to the ajax script but it just made the page refresh without submitting anything.
The ajax script is as follows:
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#FFDDAA"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var name = $("input#name").val();
var email = $("inputemail").val();
var phone = $("inputphone").val();
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "http://www.green-panda.com/website/panda/webParts/contact-form.php",
data: dataString,
success: function() {
$('#myModalLabel').html("<h3 class='text-success' id='myModalLabel'>Contact Form Submitted!</h3>")
$('#myModalSmall').html("<p class='muted'>Your submiessions are below. We will be contacting you soon, you may now close this window.</p>")
$('#submit_btn').className +=" disabled"
.hide()
.fadeIn(1500, function() {
$('#message').append("<i class='icon-ok icon-white'></i>");
});
}
});
return false;
});
});
runOnLoad(function(){
$("input#name").select().focus();
});
How could I possibly disable the inputs and button after a successful form submission?
http://jsfiddle.net/gY9xS/
Actually it's a lot simpler than what you're trying to do, you don't need to disable the inputs, simply cancel the submit after the ajax request:
$('form').submit(function(){
return false;
});
Put it inside the success handler of your ajax request.
If you want to disable the submit button, replace this wrong thing:
$('#submit_btn').className +=" disabled"
With:
$('#submit_btn').prop("disabled", true);
In my application, i just disabled the submit button and shows some progress message
function submitForm(formObj) {
// Validate form
// if (formObj.email.value === '') {
// alert('Please enter a email');
// return false;
// }
formObj.submit.disabled = true;
formObj.submit.value = 'Log In...';
return true;
}
<form class="form-login" accept-charset="UTF-8"
method="POST" action="/login" onsubmit="return submitForm(this);">
......
<input type="submit" id="login-submit" name="submit" value="Log In">
</form>

Categories

Resources