This should be simple, yet it's driving me crazy. I have an html5 form that I am submitting with ajax. If you enter an invalid value, there is a popup response that tells you so. How can I check that the entries are valid before I run my ajax submit?
form:
<form id="contactForm" onsubmit="return false;">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required placeholder="Name" />
<label for="subject">Subject:</label>
<input type="text" name="subject" id="subject" required placeholder="Subject" />
<label for="email">Email:</label>
<input type="email" name="email" id="email" required placeholder="email#example.com" />
<label for="message">Message:</label>
<textarea name="message" id="message" required></textarea>
<input type="submit" id="submit"/>
</form>
submit:
$('#submit').click(function(){
var name = $("input#name").val();
var subject = $("input#subject").val();
var email = $("input#email").val();
var message = $("input#message").val();
var dataString = 'email=' + email + '&message=' + message + '&subject=' + subject + '&name=' + name ;
$.ajax({
url: "scripts/mail.php",
type: 'POST',
data: dataString,
success: function(msg){
disablePopupContact();
$("#popupMessageSent").css("visibility", "visible");
},
error: function() {
alert("Bad submit");
}
});
});
If you bind to the submit event instead of click it will only fire if it passes the HTML5 validation.
It is best practice to cache your jQuery selectors in variables if you use it multiple times so you don't have to navigate the DOM each time you access an element. jQuery also provides a .serialize() function that will handle the form data parsing for you.
var $contactForm = $('#contactForm');
$contactForm.on('submit', function(ev){
ev.preventDefault();
$.ajax({
url: "scripts/mail.php",
type: 'POST',
data: $contactForm.serialize(),
success: function(msg){
disablePopupContact();
$("#popupMessageSent").css("visibility", "visible");
},
error: function() {
alert("Bad submit");
}
});
});
By default, jQuery doesn't know anything about the HTML5 validation, so you'd have to do something like:
$('#submit').click(function(){
if($("form")[0].checkValidity()) {
//your form execution code
}else console.log("invalid form");
});
If you are using HTML5 form validation you'll have to send the ajax request in the form's submit handler. The submit handler will only trigger if the form validates. What you're using is a button click handler which will always trigger because it has no association with form validation. NOTE: not all browsers support html5 form validation.
I prefer using the jQuery submit handler, you will still get the response to your form with the following method.
jQuery('#contactForm').on('submit', function (e) {
if (document.getElementById("contactForm").checkValidity()) {
e.preventDefault();
jQuery.ajax({
url: '/some/url',
method: 'POST',
data: jQuery('#contactForm').serialize(),
success: function (response) {
//do stuff with response
}
})
}
return true;
});
Not exactly sure what you mean. But I assume that you want to check in realtime if the input is valid. If so you should use .keyup instead of .click event, because this would lead to an action if the user presses submit. Look at http://api.jquery.com/keyup/
With this you could check the input with every new character insert and display e.g. "not valid" until your validation ist true.
I hope this answers your question!
U can also use jquery validate method to validate form like
$("#form id").validate();
which return boolean value based on form validation & also u can see the error in log using errorList method.
for use above functionality u must include jquery.validate.js file in your script
Related
This should be simple, yet it's driving me crazy. I have an html5 form that I am submitting with ajax. If you enter an invalid value, there is a popup response that tells you so. How can I check that the entries are valid before I run my ajax submit?
form:
<form id="contactForm" onsubmit="return false;">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required placeholder="Name" />
<label for="subject">Subject:</label>
<input type="text" name="subject" id="subject" required placeholder="Subject" />
<label for="email">Email:</label>
<input type="email" name="email" id="email" required placeholder="email#example.com" />
<label for="message">Message:</label>
<textarea name="message" id="message" required></textarea>
<input type="submit" id="submit"/>
</form>
submit:
$('#submit').click(function(){
var name = $("input#name").val();
var subject = $("input#subject").val();
var email = $("input#email").val();
var message = $("input#message").val();
var dataString = 'email=' + email + '&message=' + message + '&subject=' + subject + '&name=' + name ;
$.ajax({
url: "scripts/mail.php",
type: 'POST',
data: dataString,
success: function(msg){
disablePopupContact();
$("#popupMessageSent").css("visibility", "visible");
},
error: function() {
alert("Bad submit");
}
});
});
If you bind to the submit event instead of click it will only fire if it passes the HTML5 validation.
It is best practice to cache your jQuery selectors in variables if you use it multiple times so you don't have to navigate the DOM each time you access an element. jQuery also provides a .serialize() function that will handle the form data parsing for you.
var $contactForm = $('#contactForm');
$contactForm.on('submit', function(ev){
ev.preventDefault();
$.ajax({
url: "scripts/mail.php",
type: 'POST',
data: $contactForm.serialize(),
success: function(msg){
disablePopupContact();
$("#popupMessageSent").css("visibility", "visible");
},
error: function() {
alert("Bad submit");
}
});
});
By default, jQuery doesn't know anything about the HTML5 validation, so you'd have to do something like:
$('#submit').click(function(){
if($("form")[0].checkValidity()) {
//your form execution code
}else console.log("invalid form");
});
If you are using HTML5 form validation you'll have to send the ajax request in the form's submit handler. The submit handler will only trigger if the form validates. What you're using is a button click handler which will always trigger because it has no association with form validation. NOTE: not all browsers support html5 form validation.
I prefer using the jQuery submit handler, you will still get the response to your form with the following method.
jQuery('#contactForm').on('submit', function (e) {
if (document.getElementById("contactForm").checkValidity()) {
e.preventDefault();
jQuery.ajax({
url: '/some/url',
method: 'POST',
data: jQuery('#contactForm').serialize(),
success: function (response) {
//do stuff with response
}
})
}
return true;
});
Not exactly sure what you mean. But I assume that you want to check in realtime if the input is valid. If so you should use .keyup instead of .click event, because this would lead to an action if the user presses submit. Look at http://api.jquery.com/keyup/
With this you could check the input with every new character insert and display e.g. "not valid" until your validation ist true.
I hope this answers your question!
U can also use jquery validate method to validate form like
$("#form id").validate();
which return boolean value based on form validation & also u can see the error in log using errorList method.
for use above functionality u must include jquery.validate.js file in your script
I'm designing a web page which checks if an email specified is available is database. If it is available, then i must stop submitting the form.
I used ajax for live checking of email and update the response as a span message. If i click submit button, even though the email is already available in the db, the form is submitted and getting redirected to another page. Please do help me get out of this. Thanks in advance.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function checkemail() {
var email=document.getElementById( "UserEmail" ).value;
if(email) {
$.ajax({
type: 'post',
url: 'check.php',
data: {
user_email:email,
},
success: function (response) {
$( '#email_status' ).html(response);
}
});
}
}
function validateForm(){
var a=document.getElementById("email_status").innerHTML;
var b="Email Already Exist";
if(a==b)
alert('Yes');
else
alert('No');
}
</script>
</head>
<body>
<form method="POST" action="insertdata.php" onsubmit="return validateForm();">
<input type="text" name="useremail" id="UserEmail" onkeyup="checkemail();">
<span id="email_status"></span><br>
<input type="submit" name="submit_form" value="Submit">
</form>
Expected result when i give an email which is already in db:
Yes.
Actual result:
No
You code has design problems.
1.The biggest one is that you are make an ajax call request while user is typing, that will probably cause you big overhead.
2. the same design is causing the validation not working properly.
Allow me to make a proposal.
<form method="POST" action="insertdata.php" id="form" onsubmit="return false;">
<input type="text" name="useremail" id="UserEmail" >
<span id="email_status"></span><br>
<input type="submit" name="submit_form" value="Submit" onClick="checkemail();">
</form>
in this approach i have removed the keyup event form the input and have added the function checkemail() on button click.
var emails = [];
function checkemail() {
var email = document.getElementById('UserEmail').value;
if (email) {
if (!emails.includes(email)) {
$.ajax({
type: 'post',
url: 'check.php',
data: {
user_email: email,
},
success: function (response) {
$('#email_status').html(response);
if (response == 'Email Already Exist') {
console.log("email "+email+" is a spam")
emails.push(email);
} else {
document.getElementById('form').setAttribute('onsubmit', 'return true;');
document.getElementById('form').submit;
}
}
});
}else{
console.log("email "+email+" is a spam")
}
}
}
In this design approach code does
1.on button click executes checkemail function
2.checkemail function checks the emails array if contains the email from the text input, if the email is in the array then a log is written in console, if not then an ajax requset is done.
3.if the email is in the db then an other log is made, else the form is submitted.
This approach provides the ability of keeping every email that the user will possible write. I also suggest your ajax script instead of returning a text message to return a code maybe 0 or 1, that way comparison is safer.
Last but not least, although i don't know where you intend to use that code please keep in mind that a bot will probably bypass this java script code and hit directly your server side script. So you should think of a server side check also.
If you need more help or clarifications don't hesitate to ask.
I am trying to do some basic validation for a simple newsletter form I have that only requires an email. The way I have this form/input within the page, there really isn't room to add any jQuery validate error messages, so I was trying to add a simple HTML 5 required attribute, but the form submits regardless if blank.
What would be the best way to add some simple validation to this so the form checks for an email address, it is filled in, and min length of 4 characters?
<form action="" method="POST" id="newsletter-form">
<input type="email" id="footer-grid1-newsletter-input" placeholder="Your Email Address" required>
<input type="submit" id="footer-grid1-newsletter-submit" name="submit" value=' '>
</form>
$("#footer-grid1-newsletter-submit").on("click", function (event) {
event.preventDefault();
var newsletter_email = $("#footer-grid1-newsletter-input").val();
var targeted_popup_class = jQuery(this).attr('data-popup-open');
$.ajax({
url: "newsletterSend.php",
type: "POST",
data: {
"newsletter_email": newsletter_email
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to insert email!");
alert(data);
} else {
$("#newsletter-form")[0].reset();
$('.newsletter-popup').fadeIn(350).delay(2000).fadeOut();
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
The reason is because the validation is done on the submit event of the form, yet you have hooked your event to the click of the submit button. Try this:
$("#newsletter-form").on("submit", function (event) {
event.preventDefault();
// your code...
});
Working example
With regard to validating a minimum input length, you can use the pattern attribute:
<input type="email" id="footer-grid1-newsletter-input" placeholder="Your Email Address" pattern=".{3,}" required>
I followed a tutorial to adapt the code. Here I am trying trying to auto-populate my form fields with AJAX when an 'ID' value is provided. I am new to Jquery and can't get to work this code.
Edit 1 : While testing the code, Jquery isn't preventing the form to submit and sending the AJAX request.
HTML form
<form id="form-ajax" action="form-ajax.php">
<label>ID:</label><input type="text" name="ID" /><br />
<label>Name:</label><input type="text" name="Name" /><br />
<label>Address:</label><input type="text" name="Address" /><br />
<label>Phone:</label><input type="text" name="Phone" /><br />
<label>Email:</label><input type="email" name="Email" /><br />
<input type="submit" value="fill from db" />
</form>
I tried changing Jquery code but still I couldn't get it to work. I think Jquery is creating a problem here. But I am unable to find the error or buggy code. Please it would be be very helpful if you put me in right direction.
Edit 2 : I tried using
return false;
instead of
event.preventDefault();
to prevent the form from submitting but still it isn't working. Any idea what I am doing wrong here ?
Jquery
jQuery(function($) {
// hook the submit action on the form
$("#form-ajax").submit(function(event) {
// stop the form submitting
event.preventDefault();
// grab the ID and send AJAX request if not (empty / only whitespace)
var IDval = this.elements.ID.value;
if (/\S/.test(IDval)) {
// using the ajax() method directly
$.ajax({
type : "GET",
url : ajax.php,
cache : false,
dataType : "json",
data : { ID : IDval },
success : process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
}
else {
alert("No ID supplied");
}
};
function process_response(response) {
var frm = $("#form-ajax");
var i;
console.dir(response); // for debug
for (i in response) {
frm.find('[name="' + i + '"]').val(response[i]);
}
}
});
Ajax.php
if (isset($_GET['action'])) {
if ($_GET['action'] == 'fetch') {
// tell the browser what's coming
header('Content-type: application/json');
// open database connection
$db = new PDO('mysql:dbname=test;host:localhost;', 'xyz', 'xyz');
// use prepared statements!
$query = $db->prepare('select * from form_ajax where ID = ?');
$query->execute(array($_GET['ID']));
$row = $query->fetch(PDO::FETCH_OBJ);
// send the data encoded as JSON
echo json_encode($row);
exit;
}
}
I don't see where you're parsing your json response into a javascript object (hash). This jQuery method should help. It also looks like you're not posting your form using jquery, but rather trying to make a get request. To properly submit the form using jquery, use something like this:
$.post( "form-ajax.php", $( "#form-ajax" ).serialize() );
Also, have you tried adding id attributes to your form elements?
<input type="text" id="name" name="name"/>
It would be easier to later reach them with
var element = $('#'+element_id);
If this is not a solution, can you post the json that is coming back from your request?
Replace the submit input with button:
<button type="button" id="submit">
Note the type="button".
It's mandatory to prevent form submition
Javascript:
$(document).ready(function() {
$("#submit").on("click", function(e) {
$.ajax({type:"get",
url: "ajax.php",
data: $("#form-ajax").serialize(),
dataType: "json",
success: process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
});
});
I have a form that looks as following:
<form accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
<div class="field">
<label for="username">Email:</label>
<input class="text" id="passwordEmail" name="username" required="required" size="30" type="text">
<div class="field-meta">Put in your email, and we send you instructions for changing your password.</div>
</div>
<div class="field">
<input id="submitPasswordRequest" class="full-width button" name="commit" tabindex="3" type="submit" value="Get Password">
</div>
<div class="field center">
Nevermind, I Remembered
</div>
I am trying to do the post via AJAX, so I did a simple test like this:
$("#submitPasswordRequest").click(function() {
var username = $('#passwordEmail').value();
console.log(username);
/*
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: { username: username}, // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
*/
return false;
});
However it seems that the click function is not triggered and it goes to posting the form via the regular form action. What am I doing wrong here? I want to handle this via AJAX.
When you click upon the button, you simply submit the form to the back-end. To override this behavior you should override submit action on the form. Old style:
<form onsubmit="javascript: return false;">
New style:
$('form').submit(function() { return false; });
And on submit you want to perform an ajax query:
$('form').submit(function() {
$.ajax({ }); // here we perform ajax query
return false; // we don't want our form to be submitted
});
Use jQuery's preventDefault() method. Also, value() should be val().
$("#submitPasswordRequest").click(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/1/
You can also listen for the form's submit event:
$("form").submit(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/2/
jquery and ajax
$('form id goes here).submit(function(e){
e.preventDefault();
var assign_variable_name_to_field = $("#field_id").val();
...
if(assign_variable_name_to_field =="")
{
handle error here
}
(don't forget to handle errors also in the server side with php)
after everyting is good then here comes ajax
datastring = $("form_id").serialize();
$.ajax({
type:'post',
url:'url_of_your_php_file'
data: datastring,
datatype:'json',
...
success: function(msg){
if(msg.error==true)
{
show errors from server side without refreshing page
alert(msg.message)
//this will alert error message from php
}
else
{
show success message or redirect
alert(msg.message);
//this will alert success message from php
}
})
});
on php page
$variable = $_POST['field_name']; //don't use field_id if the field_id is different than field name
...
then use server side validation
if(!$variable)
{
$data['error']= true;
$data['message'] = "this field is required...blah";
echo json_encode($data);
}
else
{
after everything is good
do any crud or email sending
and then
$data['error'] = "false";
$data['message'] = "thank you ....blah";
echo json_encode($data);
}
You should use the form's submit handler instead of the click handler. Like this:
$("#formID").submit(function() {
// ajax stuff here...
return false;
});
And in the HTML, add the ID formID to your form element:
<form id="formID" accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
You need to prevent the form from submitting and refreshing the page, and then run your AJAX code:
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: $('form').serialize(), // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
return false;
});