How to prevent form resubmission alert on refresh? - javascript

I have a website with a footer in which there's a small form. There's only two things in this form: an input textbox for taking emails, and a submit button.
When user presses the Submit button, no redirection takes place, and instead an AJAX call is done to add the email to a Database table, and show the appropriate message using jQuery slideDown().
The problem is that even though no redirection to another page actually happens, still when I refresh the page sometimes, I get a browser alert that this may resubmit data. I doesn't always come, only sometimes. Don't know why.
How can I completely stop this error from coming ?
JSFiddle (See note below): http://jsfiddle.net/ahmadka/7cZZY/1/
Please note that because the footer_subscribe.php file is unaccessible from within JSFiddle, I don't get the form resubmission error here .. However the error does sometimes show up when you refresh the original actual page:
Actual page (Form is in footer section at the bottom of page): http://bit.ly/15eb2Cx
HTML Code:
<section class="subscribe">
<form class="form-wrapper cf" method="post">
<input name="email" placeholder="Enter your email here..." />
<button id="submitBtn" type="submit">Subscribe</button>
</form>
<p></p>
</section>
JavaScript Code:
$(function () {
$("#submitBtn").click(function (event) {
event.preventDefault();
event.returnValue = false;
var inputEmail = $(".subscribe input[name=email]").val();
var inputEmailTrimmed = $.trim(inputEmail);
if (inputEmail == "") {
$(".subscribe p").html("Please enter an email address.").slideDown();
} else if (inputEmailTrimmed == "" && inputEmail != inputEmailTrimmed) {
$(".subscribe p").html("Simply entering spaces won't cut it :)").slideDown();
} else {
$.ajax({
type: "POST",
url: "footer_subscribe.php",
data: {
email: inputEmail
},
success: function (data) {
if (data == "successful") {
$(".subscribe p").html("Thanks for your interest!").slideDown();
} else if (data == "already_subscribed") {
$(".subscribe p").html("This email is already subscribed.").slideDown();
} else if (data == "invalid_email") {
$(".subscribe p").html("This email is invalid.").slideDown();
} else {
$(".subscribe p").html("Something went wrong. Please try again later.").slideDown();
}
},
error: function () {
$(".subscribe p").html("Subscription is not available.").slideDown();
}
});
}
});
});

Related

How can I submit form data after preventDefault is called?

I am a little confused on how to take control of the submit event in a form, and I have tried to find a simple answer here.
I want to validate the form input before sending the form data to the form action scrip. I have tried to solve this by capturing the submit event, calling a validation script with Ajax, and if the validation succeeds I want the actual form procedure to be called. But I'm not sure how to proceed. Simply using location.replace("action.php") seems to fail (I guess that the form values aren't sent).
Here's the conceptual code:
$("form").on("submit", function(event) {
event.preventDefault();
data = {
the_input_val: $("#input_to_be_validated").val()
};
$.post("ajax_validate_input.php", data, function(data, status) {
if (status == "success") {
if (data == "invalid") {
alert("Invalid input");
// Form data is not sent... as expected
} else {
// Here I want to send the form data. But the event.preventDefault() prevents it from happening
// What do I put here to call the form's 'action' script with form data?
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="action.php">
<input id="input_to_be_validated" name="my_input" type="text">
<button type="submit" name="submit">Submit</button>
</form>
Call the submit() method on an HTMLFormElement to manually submit the form without passing through the submit event again.
The form can be retrieved by reading out the target property of the event object.
Though, to make this work, lose the name="submit" value on your button, as this will cause an error trying to submit with the method.
const $form = $("form");
$form.on("submit", function(event) {
event.preventDefault();
const data = {
the_input_val: $("#input_to_be_validated").val()
};
$.post("ajax_validate_input.php", data, function(data, status) {
if (status == "success") {
if (data == "invalid") {
alert("Invalid input");
// Form data is not sent... as expected
} else {
event.target.submit();
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="action.php">
<input id="input_to_be_validated" name="my_input" type="text">
<button type="submit">Submit</button>
</form>
You can use the submit() method like this:
if (status == "success") {
if (data == "invalid") {
alert("Invalid input");
// Form data is not sent... as expected
} else {
event.submit();
}
}

How do I submit this form without page reload?

So basically I have this interest slider plugin that calculates the repayments on a loan over a certain period of time - https://loancalc.000webhostapp.com/
But the problem I am having is submitting the form without reloading the page, currently you enter your name and email.
I have included this ajax script on line 1146 of slider.js but the slider continues to reload the page when submitting the form.
I am told it could be because i'm not enqueuing the script (for wordpress) properly.
jQuery('.qis-register').on('submit', 'input', function(){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else if (email == ""){
$("input#youremail").focus;
return false;
}
else{
jQuery.ajax({
type: "POST",
url: "quick-interest-slider.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}});
The full code is here (slider.js, quick-interest-slider.php, register.php) - https://github.com/Curnow93/quick-interest-slider/tree/master/quick-interest-slider
There's no submit event on the input. It should be on the form. Also, you need to pass the event to the callback function.
jQuery('.qis_form').on('submit', function(event) {
Also your selector doesn't select anything. I have updated it using the right selector.

Jquery ajax within a function

Hi i'm trying to use ajax to send a simple username and password to a login.php which would return 2 result being false or true. Problem is, when i click #loginbutton, it seem to be loading but nothing appears after that (no alert or page reload).
here's my script
<script>
$(document).ready(function(){
$('#loginbutton').click(function() {
$('#loginform').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(result) { // on success..
if (result == 'false') {
alert("Login failed.\n\nThe username and password doesn't match or perhaps the username doesn't exist.\n\nMake sure you have checked your email and validate your account.");
}
else if (result == 'true') {
alert("Thank you, the registration was successful. \nWe have sent you an email, please validate your account. \nClick OK and we will redirect you to the homepage.");
window.location.replace("http://127.0.0.1/wordpress/");
}
}
});
return false; // cancel original event to prevent form submitting
});
});
});
</script>
and my login form (i'm trying to integrate this with wordpress)
<?php
$templateDirectory= get_bloginfo('template_directory');
echo'
<form id="loginform" action="'.$templateDirectory.'/login.php" method="post" class="login">
LOGIN
<div class="para"><input type="text" name="uname" placeholder="Username ..." onkeydown="if (event.keyCode == 13) document.getElementById(\'loginform\').submit()"> <br><input type="password" name="pass" placeholder="Password ..." onkeydown="if (event.keyCode == 13) document.getElementById(\'loginform\').submit()"></div>
</form>';
?>
anyone can tell me what's wrong :(
You are adding a form submit handler inside a click handler... it is not required... try
$(document).ready(function () {
$('#loginform').submit(function () { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function (result) { // on success..
if (result == 'false') {
alert("Login failed.\n\nThe username and password doesn't match or perhaps the username doesn't exist.\n\nMake sure you have checked your email and validate your account.");
} else if (result == 'true') {
alert("Thank you, the registration was successful. \nWe have sent you an email, please validate your account. \nClick OK and we will redirect you to the homepage.");
window.location.replace("http://127.0.0.1/wordpress/");
}
}
});
return false; // cancel original event to prevent form submitting
});
});

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>

$posts jquery submits my form

<script type="text/javascript">
function claim()
{
var c = confirm('You sure?');
if(c)
{
var password=prompt("Please mention pw","");
if (password!=null && password!="")
{
$.post("/claim/<?php echo $refnr; ?>", { partner_pwd: password },
function(data) {
alert(data);
if(data == '1')
{
return true;
}else{
return false;
}
});
}else{
return false;
}
}else{
return false;
}
}
</script>
When testing I get to the Please mention pw, after i entered and press OK it submits my form, instead of making the $.post and only submit my form if data == '1' (return true)
claim() is called at my submit button;
<input type="submit" name="submit" onclick="return claim()"; value="Submit" />
I tried alert debugging and it was true like i thought it automatically submits when it reads the $.post(), I only wish it to submit (by returning true) if the data is 1.
Well, if you put a form in a website, it's goal is to submit the form.
http://api.jquery.com/submit/ (scroll down to the very last example starting with Example: If you'd like to prevent forms from being submitted unless a flag variable is set, try:)
As stated in the link above, you should change form's action instead of some page and do something like action="javascript:claim()". I think that should work.
The return true and return false inside of your $.post request do nothing but return out of that callback. It does not prevent the form from submitting. Instead, try preventing the submit completely and then triggering it if you want the submit to happen.
function claim() {
var c = confirm('You sure?');
if (!c) {
return false;
}
var password = prompt("Please mention pw", "");
if (password != null && password != "") {
$.post("/claim/<?php echo $refnr; ?>", {
partner_pwd: password
}, function(data) {
alert(data);
if (data == '1') {
$("#myform").submit();
}
});
}
return false;
}​
Note how we always return false out of that function regardless of the validity. If it is valid, we trigger the form's submit event directly.
Your onclick method on the submit it's not working because the form will be submitted eitherway.
You should for example set a listener on the onsubmit(); event on the form
or another solution is on the put the onsubmit attribute with your javascript function in it and submit the form from your javascript with the $('#form').submit(); function.

Categories

Resources