How can I submit form data after preventDefault is called? - javascript

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

Related

Create conditional submit using jQuery event.preventDefault()

Before submitting my form, I wan't to check if inserted dates are available. I have a php script which can perform this check and I want to call this php script via jquery/ajax.
I believe I should use event.preventDefault(); to avoid that the form is submitted. However I somehow cannot combine it with the Ajax call. The action of the form is performed anyway, the user is redirected to test.html.
What am I doing wrong? Anyone any suggestions?
My .html
<form id="checkData" action="test.html" method="post">
<input type="text" id="from" name="from">
<input type="text" id="to" name="to">
<input type="submit" value="Book">
My .js
$( "#checkData" ).submit(function( event ) {
var data = $("#checkData :input").serializeArray();
$.post("check.php", data, function(json){
if (json.status == "fail") { //this works fine without using the "event.preventDefault() statement"
event.preventDefault();
}
}, "json");
Put the preventDefault() on the click event of the submit button instead.
I didn't test the code so it might have some typo.
$( "#checkData input[type='submit']" ).click(function( event ) {
event.preventDefault();
var data = $("#checkData :input").serializeArray();
$.post("check.php", data, function(json){
if (json.status != "fail") {
$(#checkData).submit();
}
}, "json");
event.stopPropagation();
You can prevent the default behavior immediatelly.
Execute the post request.
If everything is ok, off the event submit and execute that the form submission programmatically.
if (json.status !== "fail") {
$self.off('submit', fn);
$self.submit();
}
This is the approach:
function fn(event) {
event.preventDefault();
var data = $("#checkData :input").serializeArray();
var $self = $(this);
$.post("check.php", data, function(json) {
if (json.status !== "fail") {
$self.off('submit', fn);
$self.submit();
}
}, "json");
}
$("#checkData").submit(fn);

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!') }
});

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
});
});

How to prevent form resubmission alert on refresh?

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

$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