I want to validate a form for inputs with the 'required' attributes but it appears that "e.preventDefault()" is not working. The form submits and the POST succeeds but with the unvalidated data and I can't find where the problem is.
<form>
<label for="name" class="control-label">Name</label>
<input type="text" id="name" class="form-control" required>
<label for="phone" class="control-label">Phone Number</label>
<input type="text" id="phone" class="form-control" required>
<label for="email" class="control-label">Email address</label>
<input type="email" id="email" class="form-control" required>
<div id="form-response"></div>
<button class="btn btn-lg btn-primary btn-block" id="submit" type="submit" style="background-color:#28547C;">Request Appointment</button>
</form>
JS:
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var name = $("#name").val(),
email = $("#email").val(),
phone = $("#phone").val()
$.ajax({
type: "POST",
url: 'https://a2xvt72c0c.execute-api.us-west-2.amazonaws.com/prod',
contentType: 'application/json',
data: JSON.stringify({
'name': name,
'phone':phone,
'email': email
}),
success: function(res) {
$('#form-response').html('<div class="alert alert-info" role="alert">Thank you! Appointment request has been sent. We will contact you soon. </div>');
},
error: function() {
$('#form-response').html('<div class="alert alert-info" role="alert">Something went wrong... We are working on it!</div>');
}
});
})
});
JS Fiddle: https://jsfiddle.net/yhgz55y0/
Right now you are using a click event and not a submit event. If you switch it to:
$("#submit").submit(function(e) {...
the validation works.
Your form is submitting because you are calling the $.post() immediately without stopping. You want to run validation against your name, email and phone variables and if any are not valid, return early or put the entire thing into an if block.
What e.preventDefault() does is prevents the browser built-in actions. But as your form has no action or target properties, you are effectively canceling a no-op, hence why this is not behaving as you expect it to.
preventDefault is a function that prevents a normal task from executing. Here you prevent the click on a button. A button doesn´t have a function in this form so there won´t be any difference. You want to prevent de form from submiting. If you change your code to this:
$(document).ready(function() {
$("form").submit(function(e) {
e.preventDefault();
var name = $("#name").val(),
email = $("#email").val(),
phone = $("#phone").val()
$.ajax({
type: "POST",
url: 'https://a2xvt72c0c.execute-api.us-west-2.amazonaws.com/prod',
contentType: 'application/json',
data: JSON.stringify({
'name': name,
'phone':phone,
'email': email
}),
success: function(res) {
$('#form-response').html('<div class="alert alert-info" role="alert">Thank you! Appointment request has been sent. We will contact you soon. </div>');
},
error: function() {
$('#form-response').html('<div class="alert alert-info" role="alert">Something went wrong... We are working on it!</div>');
}
});
})
});
This assuming you only have 1 form on your page. This will prevent the form from submiting.
Related
Validation part of my jQuery works, however, the AJAX part does not seem to be doing anything and I am wondering why?
It comes up with no errors and the registration works perfect without the AJAX, however, I have to use it.
HTML form in register.php:
<form method="post" action="register.php" name="registration-form" id="register-form">
<div class="form-group" id="email-group">
<label for="email"> Email address </label>
<input id="email" type="email" name="email" class="form-control" aria-describedby="emailHelp" required>
</div>
<div class="form-group" id="password-group">
<label for="password"> Password </label>
<input id="password" type="password" name="password" class="form-control" required>
</div>
<div class="form-group form-check">
<input type="checkbox" name="terms" class="form-check-input" required> I accept the <a class="privacy-link"
href="privacy-policy.php"> Privacy Policy </a>
</div>
<button type="submit" name="register_user" class="btn btn-primary" value="register_user">Register</button>
</form>
jQuery with AJAX:
$(document).ready(function () {
$("#register-form").submit(function (event) {
event.preventDefault();
}).validate({
rules: {
email: {
minlength: 6
},
password: {
minlength: 8
}
},
messages: {
email: "Email should be at least 6 characters",
password: "Password should be at least 8 characters"
},
submitHandler: function (form) {
var email = $("#email").val();
var password = $("#password").val();
$.ajax({
url: "register.php",
contentType: "application/json",
type: "POST",
data: {
email: email,
password: password
}
}).done(function (response) {
// some actions
});
}
});
});
register.php PHP to handle it:
if (isset($_POST['register_user'])) {
/* Others */
}
I tried various "isset", but to no avail.
there are few things wrong i see here.
maybe you should not catch the "submit" event of your form, i believe validation plugin take care of it.
as per the doc : https://jqueryvalidation.org/validate/#submithandler
maybe you should remove this part :
.submit(function(event) {
event.preventDefault();
})
in your ajax call, you submit 2 post variables email and password
but in your PHP file you try to retrieve $_POST['user_registration'] variable which DOES NOT EXIST because you didn't submit your form to the server's register.php file, you submitted only the 2 variables email and password
I suggest you using FormData (https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData) so you only have to update the following piece of code to make it work (in theory)
example
data = new FormData(document.getElementById('#register-form'));
$.ajax({
url: "register.php",
type: "POST",
data: data,
processData: false,
contentType: false,
})
you can refer to this SO question https://stackoverflow.com/a/8244082/5856233
I'm unable to keep my AJAX call inside the same page. It keeps posting my form without any of the tried preventDefault() tries.
Here's my full code for a form ID "#leadform" and a button ID "#submitButton".
$(document).ready(function() {
$("#submitButton").on('click', function(e) {
e.preventDefault();
$('#leadform').submit();
});
$("#leadform").validate({
rules: {
Mobile: {
required: true
},
email: {
required: true
}
},
messages: {
Mobile: {
required: "Please enter a valid phone number"
},
email: {
required: "Please enter your email address"
}
},
submitHandler: function(form) {
$("#response").addClass("alert alert-info").text("Do not close this window, it may take a minute to complete!");
var formData = $('#leadform').serialize();
$.ajax({
url: 'submit.php',
type: 'POST',
data: formData,
dataType: 'text', // json
beforeSend: function(data) {
//console.log(data);
},
success: function(data) {
$("#response").removeClass("alert-info").delay(200).addClass("alert-success").text("Thank you for your request! You can now close this window");
},
error: function(data) {
console.log('An error occurred.');
console.log(data);
}
});
return false;
}
});
});
I have tried a lot of options, read about all the SO posts and none helped.
Alternatives I tried are:
Without $('#leadform').submit(); called seperately, but from within the same function.
e.preventDefault from within the submithandler (added e to the function of course).
Tried with and without that return false line.
Whatever I tried (tried for hours literally), it goes straight to the php file. When I remove the validate function and include the ajax normally via the submit button click function, it works fine and as expected (it just won't validate my last step in the form wizzard so i need to make a validation for that last step.
I hope anybody can help me out.
Thanks.
Added HTML Section (shortened)
<form action="submit.php" name="leadform" id="leadform" method="POST" accept-charset="utf-8" class="js-wizard-validation2-form">
<div id="_Mobile" class="form-group">
<label class="control-label" for="Mobile">Mobile Number</label>
<input type="text" name="Mobile" id="Mobile" minlength="10" maxlength="16" placeholder="Phone number here" class="form-control required input_text" required="">
</div>
<div id="_Email" class="form-group">
<label class="control-label" for="Email">Email Address</label>
<input type="email" name="Email" id="Email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$" placeholder="Email here" autocorrect="off" autocapitalize="off" class="form-control input_text" required="">
</div>
<div class="block-content block-content-sm block-content-full bg-body-light rounded-bottom" style="margin-top:20px;">
<div class="row">
<div class="col-6">
<button type="button" class="btn btn-lg btn-alt-secondary" data-wizard="prev">
<i class="fa fa-angle-left mr-1"></i> Previous
</button>
</div>
<div class="col-6 text-right">
<button type="button" class="btn btn-lg btn-info" data-wizard="next">
Next<i class="fa fa-angle-right ml-1"></i>
</button>
<button type="submit" id="submitButton" class="btn btn-lg btn-success d-none" data-wizard="finish">
<i class="fa fa-check mr-1"></i> Submit </button>
</div>
</div>
</div>
</form>
According to the docs, you can actually trigger the validator without submitting the form.
var validator = $( "#leadform" ).validate();//your entire validation script goes here, its left out for brevity
$("#submitButton").on('click', function(e) {
e.preventDefault();
validator.form();
});
I am trying to create a user settings page where a user inputs his/her information, clicks "save", then the page saves the data without clearing the inputted fields or reloading the page. The best example I can think of is the user account settings page on Udemy.
A LOT of the similar questions I've looked at are using php or renders data in a div below the form. I want the data to remain IN the form inputs. I'm using nodejs, express, bodyparser.
<form id="updateAccSettings" action="/account" method="POST">
<div class="form-group">
<label for="address">Address* </label>
<input class="form-control" type="text" name="address" placeholder="Address" required/>
</div>
<div class="form-group">
<label for="address2">Address 2 </label>
<input class="form-control" type="text" name="address2" placeholder=""/>
</div>
<div class="form-group">
<label for="city">City* </label>
<input class="form-control" type="text" name="city" placeholder="City" />
</div>
<div class="form-group">
<input type="submit" name="save" class="btn btn-lg btn-primary btn-block" value="Save"/>
</div>
</form>
I've tried this with AJAX
$(document).ready(function() {
$("#updateAccSettings").on("submit", function(e){
e.preventDefault();
var details = $("#updateAccSettings").serialize();
$.post("/account", details, function(data){
$("#updateAccSettings").html(data);
});
});
});
and this
$(document).ready(function () {
$("#updateAccSettings").bind("submit", function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/account",
data: $("#updateAccSettings").serialize(),
success: function(){
alert("You've successfully updated your account settings.")
}
});
});
});
And I have this for my app.js
app.post("/account", function(req, res) {
var address = req.body.address;
var address2 = req.body.address2;
var city = req.body.city;
var updateAccount = {address: address, address2: address2, city: city};
account.push(updateAccount);
console.log("Updated data");
res.redirect("/settings/account");
});
When I clicked save, I get a Cannot read property of 'push' undefined. I tried deleting the var address, var address2, etc and keeping only the console.log which logs whenever I click save but doesn't keep the data in the input. I tried adding onsubmit="return false" as an attribute on the form tag but the console.log doesn't run when I click save so I assume it's not doing anything with the data.
Not sure how to proceed from here. All my other forms use modals or render results in another page.
You're getting the error because you're trying to push onto an undefined variable. Namely in the last section when posted this app.post:
app.post("/account", function(req, res) {
var address = req.body.address;
var address2 = req.body.address2;
var city = req.body.city;
var updateAccount = {address: address, address2: address2, city: city};
account.push(updateAccount); // error is being thrown here
console.log("Updated data");
res.redirect("/settings/account");
});
Once you have a dummy variable for account, you can send back to the frontend a json response to be read in the form success handler.
Example code: (I haven't tested it)
Backend:
app.post("/account", function(req, res) {
var account = [];
var address = req.body.address;
var address2 = req.body.address2;
var city = req.body.city;
var updateAccount = { address, address2, city };
account.push(updateAccount); // error is being thrown here
console.log("Updated data");
res.json(updateAccount);
});
Frontend:
$(document).ready(function () {
$("#updateAccSettings").bind("submit", function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/account",
data: $("#updateAccSettings").serialize(),
success: function(data){
$('#address').value(data.address);
$('#address2').value(data.address2);
$('#city').value(data.city);
}
});
});
});
You could give each of your form input fields an id (e.g the same as their "name" property)and get their values individually when doing the ajax request as follows (that way you can reinsert the values after the form is submitted):
HTML
<form id="updateAccSettings" action="" method="POST">
<div class="form-group">
<label for="address">Address* </label>
<input class="form-control" type="text" name="address" id="address" placeholder="Address" required/>
</div>
<div class="form-group">
<label for="address2">Address 2 </label>
<input class="form-control" type="text" name="address2" id="address2" placeholder=""/>
</div>
<div class="form-group">
<label for="city">City* </label>
<input class="form-control" type="text" name="city" id="city" placeholder="City" />
</div>
<div class="form-group">
<input type="submit" name="save" class="btn btn-lg btn-primary btn-block" value="Save"/>
</div>
</form>
JQuery
$(document).ready(function() {
$("#updateAccSettings").on("submit", function(e){
e.preventDefault();
//get the values of our input fields and store them in local variables
var address = $("#address").val();
var address2 = $("#address2").val();
var city = $("#city").val();
//prepare the data object to send in the ajax request
var params = {"address": address, "address2": address2, "city" : city};
$.ajax({
type: "POST",
url: "/account",
data: JSON.stringify(params),
dataType: "json",
success: function(data){
//the ajax request was successful
//We can do something with the data we get back here.
//Also we can reinsert the values (that were submitted) to the form
$("#address").val(address);
$("#address2").val(address2);
$("#city").val(city);
},
error: function(xhr, status, error) {
//an error occured in the request so handle it here
}
});
});
});
I have form which contain email input field
<form id="TypeValidation" action="" method="post" enctype='multipart/form-data'>
<div class="form-group has-label col-sm-6">
<label>
Email
</label>
<input class="form-control" name=email" type="email" required>
</div>
<div class="card-footer text-center">
<button type="submit" name="add_usr_acc" id="add_usr_acc" value="add_usr_acc" class="btn btn-primary" >Add</button>
</div>
</div>
</form>
Issue is that in script code when alert on email then come undefined. how to get value in which user type a email
<script>
$("#TypeValidation").on('submit', (function(e) {
var email = $(this).find('input[name="email"]').val();
alert(email); {
e.preventDefault();
$.ajax({
url: "fn_acc_submit.php?addUsraccID=" + addUsraccID,
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
dataType: "html",
beforeSend: function() {
$("#add_usr_acc").prop('disabled', 'disabled')
},
success: function(result) {
alert(result);
location.reload();
if (result == '1') {
location.replace("lst_user_account.php");
} else {
location.replace("add_user_account.php");
}
}
});
}
}));
</script>
Please fix my problem where I am doing wrong.
Problem is in your HTML code at below line:
<input class="form-control" name=email" type="email" required>
Here name=email" is not valid.
Change this to name="email"
In you input field, it should name="email". You forgot to add opening quotes.
I'm a novice coder, and i'm having trouble putting a simple form together using validator.js
Basically since trying to build in the validation the form has stopped working, my guess is the 'data: $('#send-form').serialize(),' has not got the correct path or syntax, but i could be wrong.
As soon as i add:
$.ajax({
type: "POST",
url: "process.php",
data: $('#send-form').serialize(),
}
the alerts do not fire!
<form class="contact" name="contact" id="send-form" data-toggle="validator" role="form" >
<div class="form-group">
<label class="subTitle" for="name">NAME</label><br>
<input type="text" name="name" class="form-control" placeholder="Enter your full name" data-error="Please enter your name" required>
<div class="help-block with-errors"></div><br>
</div>
<div class="form-group">
<label class="subTitle" for="email">E-MAIL</label><br>
<input type="email" name="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,3}$" class="form-control" placeholder="Enter a valid email address" data-error="Invalid email address" required>
<div class="help-block with-errors"></div><br>
</div>
<div class="form-group">
<button type="submit" class="subBtn form-control">SUBMIT YOUR ENQUIRY</button>
</div>
</form>
<script>
$('#send-form').validator().on('submit', function (e) {
if (e.isDefaultPrevented()) {
alert('form is not valid');
} else {
// everything looks good!
e.preventDefault();
alert('form is valid');
// your ajax
$.ajax({
type: "POST",
url: "process.php",
data: $('#send-form').serialize(),
}
});
</script>
Should be:
$('#send-form').validator().on('submit', function (e) {
if (e.isDefaultPrevented()) {
alert('form is not valid');
} else {
// everything looks good!
e.preventDefault();
alert('form is valid');
// your ajax
$.ajax({
type: "POST",
url: "process.php",
data: $('#send-form').serialize(),
});
}
});
(untested)