Link to home
Create AccountLog in
Avatar of bigeven2002
bigeven2002Flag for United States of America

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.
<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>

Open in new window


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

Open in new window


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

Open in new window

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

There may be other things in play here, but it looks like the PHP script doesn't "do anything."  It defines a function and assigns some variables, but never produces any output.  We would expect that the PHP script would write something back to the browser.

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.
<!DOCTYPE html>
<!-- http://iconoun.com/demo/popup_video_example.php -->
<html dir="ltr" lang="en-US">
<head>

<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Experimental Popup / Overlay Video</title>

<style type="text/css">

/* TRANSLUCENT OVERLAY GRAYS-OUT THE VIEWPORT */
.spw_overlay {
    width: 100%;
    background: rgba(0,0,0,.6);
    position: absolute;
    left: 0;
    top: 0;
}

/* CONTAINER FOR THE VIDEO - ROUNDED CORNERS */
.spw_videobox {
    position: absolute;
    background: white;
    text-align: center;
    padding: 20px;
    border-radius: 5px;
}

/* THE VIDEO INSIDE THE VIDEO BOX CONTAINER */
.spw_videobox video {
    width: 640px;
}

/* SMALL CIRCLE-X AT UPPER RIGHT OF VIDEOBOX - IE CANNOT USE CLEAR-TEXT SVG; REQUIRES BASE64_ENCODE() */
.spw_close {
    width: 24px;
    height: 24px;
    position: absolute;
    top: -12px;
    right: -12px;
    display: block;
    border-radius: 12px;
 /* background: white url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><text x="5" y="18" font-size="18" font-family="verdana" font-weight="bold" fill="gray">X</text></svg>') no-repeat center center; */
    background: white url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjx0ZXh0IHg9IjUiIHk9IjE4IiBmb250LXNpemU9IjE4IiBmb250LWZhbWlseT0idmVyZGFuYSIgZm9udC13ZWlnaHQ9ImJvbGQiIGZpbGw9ImdyYXkiPlg8L3RleHQ+PC9zdmc+') no-repeat center center;
}
.spw_close:hover {
    cursor: pointer;
 /* background: gray url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><text x="5" y="18" font-size="18" font-family="verdana" font-weight="bold" fill="white">X</text></svg>') no-repeat center center; */
    background: gray url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjx0ZXh0IHg9IjUiIHk9IjE4IiBmb250LXNpemU9IjE4IiBmb250LWZhbWlseT0idmVyZGFuYSIgZm9udC13ZWlnaHQ9ImJvbGQiIGZpbGw9IndoaXRlIj5YPC90ZXh0Pjwvc3ZnPg==') no-repeat center center;
}

</style>

</head>

<body>
<div class="wrapper">
  <header>
    <div class="container">
    <h1 class="col-lg-9">Video Windows</h1>
    </div>
  </header>
  <div class="container">
  <p>Click on the link below to view video and description in a popup</p>

    <ul>
      <li><a class="spw_video-link" href="http://techslides.com/demos/sample-videos/small.mp4" data-description="This is the description for sample video #2">HTML5 Video 2</a></li>
      <li><a class="spw_iframe-link" href="https://www.youtube.com/embed/zr9leP_Dcm8?autoplay=1" width="620" height="315" data-description="This is the YouTube video #3">Youtube Iframe embed</a></li>
    </ul>

  </div><!-- /container -->
</div><!-- /wrapper -->
<footer>
</footer>

<script src="http://code.jquery.com/jquery.js"></script>

<script>

$(function(){

    // ESCAPE KEY WILL REMOVE THE OVERLAY
    $(document).on('keyup',function(e){
        if (e.keyCode == 27) {
            $('.spw_overlay').remove();
        }
    });

    // CLICK ON THE OVERLAY OR CLOSE BUTTON BODY WILL REMOVE THE OVERLAY
    $('body').on('click', '.spw_overlay, .spw_close', function(){
        $('.spw_overlay').remove();
    });

    // CLICK ON THE VIDEOBOX ONLY AFFECTS VIDEOBOX: http://www.w3schools.com/JQuery/event_stoppropagation.asp
    $('body').on('click','.spw_videobox', function(e){
        e.stopPropagation();
    });

    // FOR HTML5 VIDEO TAGS
    $('.spw_video-link').click(function(e){
        var el = $(this);

        // TURN OFF THE EXPECTED ACTION (REDIRECT BROWSER TO LINK)
        e.preventDefault();

        // CREATE THE VBOX DOM ELEMENT
        var vbox =  $('<div/>').addClass('spw_videobox');

        // ADD CLOSE-LINK, VIDEO BOX, AND DESCRIPTION
        vbox.append($('<a/>').addClass('spw_close'));
        vbox.append($('<video/>').prop({autoplay: true, controls: true}).attr('src', el.attr('href')));
        vbox.append($('<div/>').html(el.data('description')));

        // GRAY OUT THE BODY, THEN ADD THE VBOX DOM ELEMENT
        $('body').append(
            $('<div class="spw_overlay"/>').height(Math.max($(document).height(), $(window).height()))
            .append( vbox ) );

        // POSITION THE VBOX NEAR THE TOP CENTER
        var left = ($(window).width() - vbox.width()) >> 1;
        var top  = $(window).scrollTop() + 50;
        vbox.css({
            left: left + 'px',
            top: top + 'px'
        });
    });

    // FOR IFRAME EMBEDDING
    $('.spw_iframe-link').click(function(e){
        var el = $(this);

        // TURN OFF THE EXPECTED ACTION (REDIRECT BROWSER TO LINK)
        e.preventDefault();

        // CREATE THE FBOX DOM ELEMENT
        var fbox =  $('<div/>').addClass('spw_videobox');

        // ADD CLOSE-LINK, IFRAME, AND DESCRIPTION
        fbox.append($('<a/>').addClass('spw_close'));
        fbox.append($('<iframe/>').attr('src', el.attr('href')).attr('width', '640').attr('height', '360'));
        fbox.append($('<div/>').html(el.data('description')));

        // GRAY OUT THE BODY, THEN ADD THE FBOX DOM ELEMENT
        $('body').append(
            $('<div class="spw_overlay"/>').height(Math.max($(document).height(), $(window).height()))
            .append( fbox ) );

        // POSITION THE FBOX NEAR THE TOP CENTER
        var left = ($(window).width() - fbox.width()) >> 1;
        var top  = $(window).scrollTop() + 50;
        fbox.css({
            left: left + 'px',
            top: top + 'px'
        });
    });
});

</script>

</body>
</html>

Open in new window

Hope that helps, and Merry Christmas.
Avatar of bigeven2002

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.
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...
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Great thanks!  I will give this a shot and report back later.
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
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.
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
Will do thanks!