Disable form inputs after ajax submission - javascript

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>

Related

Refresh form after AJAX call

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>

Not able to submit or not submit form after ajax response

I am trying to submit a form after validation and confirmation. But after the validation the form is not getting submitted. If I do not validate and confirm then the form is being submitted. What am I doing wrong here? Please tell me how to rectify it.
<div class="button secondary" id="contact_submit">
Create/Update <span class="icon-right icon-check"></span>
</div>
function validateFields() {
#some validation operations
if(validated){
if(operation == "Create"){
$("#contact-form")[0].setAttribute("action", "/contact/create_contact/");
$("#contact-form")[0].setAttribute("method", "POST");
}
else if(operation == "Update"){
$("#contact-form")[0].setAttribute("action", "/contact/" + object_id + "/update_contact/");
$("#contact-form")[0].setAttribute("method", "PATCH");
}
$('#contact-form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: '/oms/getIsPrimaryContact/',
type: 'GET',
data: { object_id: object_id },
success: function(data) {
if ($('.element-contact#is_primary_contact').prop("checked") && !data.is_primary_contact) {
var c = confirm('Are you sure you want to change the primary contact?');
if (c) {
return true;
} else {
return false;
}
}
},
error: function() {} });
});
$('#contact-form').submit();
}
}
$(document).ready(function(){
$("#contact_submit").click(function(e) {
validateFields()
});
});
It just shows the confirmation box and if I click on ok or cancel then also the ajax call is being initiated. If the checkbox is not checked then also the form is not being submitted.
On clicking either button in the confirmation box the form should be submitted or not submitted and if the checkbox is not checked then the form should just be submitted.
But instead ajax call is happening on clicking any button.

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>

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

jquery ajax call after javascript validation function

I am trying to call my ajax code after my js validate() methods returns true on submit of the searchId button. But the ajax code is not executing. if I place an alert there it works fine.
Where I am doing wrong? Please help!!
here is my javascript code
<script language="JavaScript">
function validate()
{
var msg = "";
//all my field validations are here
msg += "o Name is not a valid name.\n";
if (msg > "") {
alert(msg);
return false;
}
else {
return true;
}
}
$(document).ready(function(){
$("#simple-post").click(function()
{
$("#ajaxform").submit(function(e)
{
// getting the values of both firstname and lastname
var beginDate = $('input[name="txtBeginDate"]').val();
var endDate = $('input[name="txtEndDate"]').val();
var mdnVal = $('input[name="txtMsid"]').val();
// posting the values
var dataString = 'beginDate=' + beginDate + '&endDate=' + endDate+ '&mdnVal=' + mdnVal;
alert(dataString);
var formURL = $(this).attr("action");
//alert(formURL);
$.ajax(
{
url : formURL,
dataType:'json',
async: false,
data: dataString,
beforeSubmit: validate,
success:function(data){
queryObject = eval('(' + JSON.stringify(data) + ')');
queryObjectLen = queryObject.empdetails.length;
drawChart();
},
error : function(xhr, type) {
alert('server error occoured')
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
});
});
Here is my HTML code
<form name="ajaxform" id="ajaxform" action="getData.jsp" onSubmit="return validate();" method="POST">
<Table>
<input type="submit" name="action" value="Search" id="searchId">
<input type="text" name="name" id="id" size="10" maxlength="10">
//other input fields
</table>
</form>
<button class="btn btn-info" id="simple-post">Run Code</button>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
UPDATE
I have updated my code, i can submit my form, but the validation not working. I am using beforeSubmit: validate, still i dont see my validation messages. Please help.
I fxed the problem. Added a Submit button markup and removed Run Code. Changed onsubmit to onclick on the submit button. Again removed $("#simple-post").click(function() form my jquery code.This seems to be working fine now.
Thanks to this post
Validate a form with javascript before submitting with ajax?

Categories

Resources