bigeven2002
asked on
How do I add form validation to this code?
I have an AJAX based contact form that I am testing. Using bootstrap and jQuery, the link is called in a modal window. I have the form working and it will send email provided I fill in the fields correctly, but I haven't been able to figure out how to display an error message if validation fails.
The validation criteria is email and message files must not be blank and the email field must contain a valid formatted address. Please see the following code for what I have.
HTML - I have a div ID set for form-ok and form-err. I can get form-ok to appear but I don't know how to get form-err to appear if validation fails.
JavaScript
PHP called by the form action, it counts the errors if any and returns the value from the function. The if statements below are not functional.
The validation criteria is email and message files must not be blank and the email field must contain a valid formatted address. Please see the following code for what I have.
HTML - I have a div ID set for form-ok and form-err. I can get form-ok to appear but I don't know how to get form-err to appear if validation fails.
<a href="#contact" data-toggle="modal" class="navbar-text">Contact</a>
<div class="modal fade" id="contact" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form id="contact-form" class="form-horizontal ajax" role="form" action="proc-contact.php" method="post">
<div class="modal-header">
<h4>Contact Me <a class="close" data-dismiss="modal">x</a></h4>
</div>
<div id="form-ok" class="alert alert-success">Thank You for your message. I will reply as soon as possible.</div>
<div id="form-err" class="alert alert-danger">Sorry there was an error sending your message. Please check your entry.</div>
<div class="modal-body" id="modal-body-id">
<div class="form-group">
<label for="contact-email" class="col-sm-2 control-label">E-mail:</label>
<div class="col-sm-10">
<input type="email" name="email" class="form-control" id="contact-email" placeholder="you@example.com">
</div>
</div>
<div class="form-group">
<label for="contact-message" class="col-sm-2 control-label">Message:</label>
<div class="col-sm-10">
<textarea name="message" placeholder="Type your message..." id="contact-message" class="form-control" rows="6"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<a class="btn btn-primary" data-dismiss="modal">Close</a>
<button class="btn btn-primary" id="new-message" type="reset">New Message</button>
<button class="btn btn-primary" value="1" name="submit" type="submit" id="submit">Send Message</button>
</div>
</form>
</div>
</div>
</div>
JavaScript
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
$('#form-ok').show();
$('#modal-body-id').hide();
$('#submit').hide();
$('#new-message').show();
//
}
});
return false;
});
$(document).ready(function(){
$('#form-ok').hide();
$('#form-err').hide();
$('#new-message').hide();
$("#new-message").click(function(){
$("#contact-form")[0].reset();
$('#modal-body-id').show();
$('#new-message').hide();
$('#submit').show();
$('#form-ok').hide();
$('#form-err').hide();
});
});
PHP called by the form action, it counts the errors if any and returns the value from the function. The if statements below are not functional.
<?php
if($_POST["submit"]) {
function chkEmlForm($frm) {
$error = 0;
$c_email = filter_var($frm['email'], FILTER_SANITIZE_EMAIL);
$c_message = filter_var($frm['message'], FILTER_SANITIZE_STRING);
$c_array = array($c_email,$c_message);
foreach($c_array as $chk):
if($chk==""):
$error++;
endif;
endforeach;
if(!filter_var($c_email, FILTER_VALIDATE_EMAIL)):
$error++;
endif;
if($error == 0):
$toEmail = "me@domain.com";
$subject = "Message from website";
$headers = "from: ".$c_email."\nReply-To: ".$c_email;
$content = "*** THIS MESSAGE IS FROM THE WEBSITE ***\n\n"
."Email: ".$c_email."\n\n"
.stripslashes(trim($c_message));
mail($toEmail,$subject,$content,$headers);
endif;
return $error;
}
$err = chkEmlForm($_POST);
if($err > 0):
$result='<div id="form-alert" class="alert alert-danger">Sorry there was an error sending your message. Please check your entry.</div>';
else:
$result='<div id="form-alert" class="alert alert-success">Thank You for your message. I will reply as soon as possible1.</div>';
endif;
}
?>
ASKER
Thanks Ray and Merry Christmas to you too. Actually I am experienced with PHP, it is just the Ajax part I need help with. In the PHP code, the mail function works and sends the email provided that the form contains a valid emails address and message as that is what is called from the HTML form action (proc-contact.php).
The problem is the form errors are ignored so if I leave the form blank, the Ajax still proceeds as if the message is successful even though PHP code failed validation. So basically if I leave the form blank, nothing happens on the PHP side since the $err var would be > 0 but the Ajax form still shows success since I don't know how to have PHP tell the Ajax that validation failed.
The user wouldn't know that it failed. But if the form was filled out correctly, then it will send the email since $err = 0 and ajax displays notification message successful.
The problem is the form errors are ignored so if I leave the form blank, the Ajax still proceeds as if the message is successful even though PHP code failed validation. So basically if I leave the form blank, nothing happens on the PHP side since the $err var would be > 0 but the Ajax form still shows success since I don't know how to have PHP tell the Ajax that validation failed.
The user wouldn't know that it failed. But if the form was filled out correctly, then it will send the email since $err = 0 and ajax displays notification message successful.
Yeah, I always have to look up jQuery, too. The general theory is that when an event handler returns FALSE, the event is not fired. So if the form fails validation, the validation function should return FALSE and that would prevent form submit.
I'll see if I can find an AJAX example...
I'll see if I can find an AJAX example...
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER
Great thanks! I will give this a shot and report back later.
SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER
Thank you both. Even though the answers provided were still over my head, it made me realize I cannot take shortcuts. I will have to start with jQuery and AJAX 101. Guess it was like I was trying to read a book starting with Chapter 12.
In the meantime, I used a quick and dirty way for validation which was adding the required="required" parameter to both form input elements. This will work if the user has JavaScript on but I have no graceful degradation. I can figure that out later once I better understand the above.
In the meantime, I used a quick and dirty way for validation which was adding the required="required" parameter to both form input elements. This will work if the user has JavaScript on but I have no graceful degradation. I can figure that out later once I better understand the above.
Thanks 4 de points, , , Please consider that the browser server communication of AJAX is really NOT an option for mobil proficient web sites now in 2016, but nearly a requirement, , you gotta use AJAX.
So have the basics of javascript programming, and the basics of JQuery programming, before you tackle a much more complex "interaction exchange" programming for AJAX. U can do copy and paste for ajax and get some pages that do work. BUT a "GOOD" interactive web site, needs much more than a simple server exchange. Please consider the ajax server text IF TESTS that I showed -
if( phpText == "!email" ) {
as being ONE way to see what happens on the server code (database, etc) and change the DYNAMIC interactive web page to many different server results and errors, so the page is a modern web interface.
Although you can find many places to learn javascript and jquery, you might should use some of the w3schools teach examples that have the "Try it Yourself" programming experimental, to see what you can do.
for w3schools jquery ajax -
http://www.w3schools.com/jquery/jquery_ajax_intro.asp
So have the basics of javascript programming, and the basics of JQuery programming, before you tackle a much more complex "interaction exchange" programming for AJAX. U can do copy and paste for ajax and get some pages that do work. BUT a "GOOD" interactive web site, needs much more than a simple server exchange. Please consider the ajax server text IF TESTS that I showed -
if( phpText == "!email" ) {
as being ONE way to see what happens on the server code (database, etc) and change the DYNAMIC interactive web page to many different server results and errors, so the page is a modern web interface.
Although you can find many places to learn javascript and jquery, you might should use some of the w3schools teach examples that have the "Try it Yourself" programming experimental, to see what you can do.
for w3schools jquery ajax -
http://www.w3schools.com/jquery/jquery_ajax_intro.asp
ASKER
Will do thanks!
This article shows the basics of a jQuery / AJAX interaction. If you follow the variables through the client and server sides of the interaction you can see how the data gets sent from the client browser and received on the server, then a response is sent back to the browser via PHP echo.
https://www.experts-exchange.com/articles/10712/The-Hello-World-Exercise-with-jQuery-and-PHP.html
There are a lot of moving parts to an application like this, and it's best to deconstruct the app into more atomic tasks. In general terms, on the client side you will use HTML for semantic markup, CSS for visual control, and JavaScript for animation and communication. On the server side, you use PHP (and usually a database) to respond to the requests sent by the client. The whole client-server relationship is described in this article. You may find it helpful.
https://www.experts-exchange.com/articles/11271/Understanding-Client-Server-Protocols-and-Web-Applications.html
If you're new to PHP and want to find some good learning resources, this article can help. If you want to save some time and you're already familiar with the principles of application design and programming, just skip over the computer science parts you already know.
https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html
There are many good ways to learn JavaScript and jQuery. I would generally recommend learning JavaScript first (or at least the basics about variable assignment, scope, object notation, etc). Online resources abound.
https://www.google.com/#q=learn+javascript
If you like to learn from books, these are two of my favorites. You would not need any others.
http://www.amazon.com/dp/0596517742
http://www.amazon.com/dp/0596805527
Moving on to jQuery, I don't have a book preference - the online resources are pretty good.
https://www.google.com/#q=learn+jquery
It's often useful to add comments to your code. This little snippet shows how comments can be used to explain your intentions. It's not directly applicable to your problem, but it gives a useful design, showing how all of the client-side HTML, CSS and JavaScript can be integrated into a single script. When I'm building an app for the first time, I like to do it this way. With everything in a single file, it's easy to share with others, get advice, make changes, etc., without having to work with several directories and script files.
Open in new window
Hope that helps, and Merry Christmas.