Form Submitting Via AJAX Despite Failing Validation - javascript

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

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>

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 to check unique username before form submission

I have been trying this for hours now. I want to check if the username already exist in DB or not. If it does, alert and don't submit. If it doesn't, submit. Here is my code.
$(function() {
$("#new_user").on("submit", function() {
var anyFieldIsEmpty = $('.newuser_input').filter(function() {
return $.trim(this.value).length == 0;
}).length > 0;
if (anyFieldIsEmpty) {
alert("There are empty fields!");
return false;
}
else {
check_curr_username();
return false;
}
});
});
function check_curr_username() {
var username = $("#user_username").val();
$.ajax({
"url": "/checkusername",
"data": {"name":username},
"type": "get",
"dataType": "json",
"success": function(data) {
alert('Username'+' '+data.username +' '+'is already taken' );
$("#user_username").focus();
return false;
},
"error": function() {
$("#new_user").submit();
return true;
}
});
}
This is a Rails form. The code is only working when the username already exist. But if not then the form is not submitting.
we need the checkusername page but i think that the form isn't submitted because error isn't triggered (ie: no error happened).
checkusername page should return a specfic value if the username is not already used then you can process the form.
This is how I check for unique username. I may get down-voted because it's not Rails, but PHP.
<style>.nodisplay{display: none;}</style>
<form id="usersigningup" name="usersigningup" method="post" action="">
<input type='text' name='name' id='nose' pattern='[A-Za-z0-9_]{5,20}' required>
<input type='text' name='password' id='password' pattern='[A-Za-z0-9_]{5,20}' required>
<input class="nodisplay" type="submit" id="usersignup" name="usersignup" value="Go!"></form><br>
<span id='response'></span>
In my CSS the default display for the submit button is set to none. next I use a javascript keyup function to collect the input field of id='nose' (which is the username) and send an ajax post to php which then runs a query on my database.
$(document).ready(function(){
$('#nose').keyup(function(){
var name = $('#nose').val();
$.ajax({
type: 'post',
data: {ajax: 1,name: name},
success: function(response){
$('#response').html(response);
}});});});
Next I use a mysqli query.
<?php include ('connect.php'); if( isset($_POST['ajax']) && isset($_POST['name']) ){
$un = $_POST['name'];
$sql51 = mysqli_query($conn, "SELECT username FROM mysite Where username = '$un'");
if (mysqli_num_rows($sql51) > 0) {
echo "<font color='red'>Sorry <b><i>" . $un . "</i></b> has been taken</font><script>document.getElementById('usersignup').style.display='none';</script>";
} else {
echo "<font color='green'><b>The Username <i>" . $un . "</i> is available</b></font><script>document.getElementById('usersignup').style.display='block';</script>";}
exit;}?>
Notice the 'if' statement in the query; this will either run one of two scripts. The first will be to keep the display of the submit button as none if there is an exact match and echo 'Sorry (username) has been taken' in an html element with the id='response'. The second script will echo 'The username (username) is available' and set the display of the submit button style to 'display:block'; making it clickable.
As I said this all happens on a keyup event so the query runs everytime you press a key and let it up you will see the characters you type in the response element; along with seeing the submit button or not.
The PHP in this example is meant as an example and not to be considered safe from hackers; although, there is a pattern attribute set in the form disallowing most characters. I hope this helps.

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