Form and validation on same page

I have coded m any forms where the validation and send of the form is sent to a separate php. What is the code so that the everything is done within the same page using php and javascript.
Thanks
HidesignAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Aaron TomoskySD-WAN SimplifiedCommented:
Adding js validation is the same. The trick in php is to start with an if post submit var is true, then put the second page code. For the else put your initial form.
0
HidesignAuthor Commented:
Thanks - do you have the exact code for this so I can see the flow
0
Aaron TomoskySD-WAN SimplifiedCommented:
Not now as I'm on my phone. But I'm sure someone will pop up with code.
0
The Ultimate Tool Kit for Technolgy Solution Provi

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy for valuable how-to assets including sample agreements, checklists, flowcharts, and more!

Dave BaldwinFixer of ProblemsCommented:
Below is my PHP email demo code that has all the elements you're asking about in basic form.  Save it as 'Email.php', put your own email address in there and you can run it.  In this code, the 'name' of the submit button is 'send' so that's what I'm checking to see if there is a valid email to send.
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');

# some settings of POST vars
if (!isset($_POST['send']))  $send = ''; else $send = $_POST['send'];
if (!isset($_POST['toText'])) $toText = ''; else $toText = $_POST['toText'];
if (!isset($_POST['ccText'])) $ccText = ''; else $ccText = $_POST['ccText'];
if (!isset($_POST['subjectText'])) $subjectText = ''; else $subjectText = $_POST['subjectText'];
if (!isset($_POST['msgText'])) $msgText = ''; else $msgText = $_POST['msgText'];
if (!isset($_POST['ccText'])) $ccTexth = ''; else $ccText = $_POST['ccText'];
if (!isset($_POST['bccText'])) $bccText = ''; else $bccText = $_POST['bccText'];
if (!isset($_POST['nameText'])) $nameText = ''; else $nameText = $_POST['nameText'];
if (!isset($_POST['fromText'])) $fromText = ''; else $fromText = $_POST['fromText'];

if ($send == "") {
    $title="Test Email Page";
    $announce="---";
}
else {
	if($fromText === "") die("No name!");
  $toText="youremail@yourdomain.com";
	$title="Test Email Page";
  $announce="Your Message has been Sent!";
	$header = "From: ".$fromText."\r\n";
//	$header .= "Cc: ".$ccText."\n";
	$header .= "Reply-To : ".$fromText."\r\n";
	$header .= "Return-Path : ".$fromText."\r\n";
	$header .= "X-Mailer: PHP\r\n";
	$header .= "MIME-Version: 1.0\r\n";
	$header .= "Content-Type: text/plain; charset=iso-8859-1\r\n";
//	ini_set(sendmail_from,$fromText);  
	mail($toText, $subjectText, $msgText, $header, '-f'.$fromText);
//	ini_restore(sendmail_from);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title><?php echo($title)?></title>
<style type="text/css">
<!-- 
A:link { color: #999999; }
A:visited { color: #999999; }
A:hover {color: #0099ff;}
-->
</style>
<script type="text/javascript">
<!--
function check()
{
var at=document.getElementById("fromText").value.indexOf("@");
var eml=document.getElementById("fromText").value;
var nam=document.getElementById("nameText").value;
var alerttxt="";
var submitOK="true";

if (eml.length < 5 || at == -1)
    {
    alerttxt=alerttxt+"Please enter a valid e-mail address!\r\n";
    submitOK="false"
    //return false;
    }
if (nam.length < 3)
    {
    alerttxt=alerttxt+"Please enter your name.\r\n";
    submitOK="false"
    //return false;
    }
if (submitOK=="false")
    {
    alert(alerttxt);
    return false;
    }

}
// -->
</script>
</head>

<body bgcolor="#ddeedd">
<div align="center">
<table border="0" cellpadding="0" cellspacing="0" summary="" width="580">
<tr><td align="center">

<?php
if ($send != "") {
   	echo ("To: ".$toText."<br>\r\nSubject: ".$subjectText."<br>\r\n".$msgText."<br>\r\n".$header);
		}
?>

<p><b><font color="#000000" size="5">Test Email</font></b></p>
<font size="4" color="#000000">

<!--   <form method="POST" action="<?php echo($PHP_SELF)?>"> -->
<form method="POST" action="Email.php" onsubmit="return check();">
    <p><font size="3"><b>Name: <input type="text" name="nameText" id="nameText" size="46"></b></font></p>
    <p><font size="3"><b>Email: <input type="text" name="fromText" id="fromText" size="46"></b></font></p>
    <input type="hidden" name="subjectText" value="Web Mail">
    <p><font face="Arial" size="3"><b>Message Text:</b></font></p>
    <p><font face="Arial" size="3"><b><textarea rows="6" name="msgText" cols="60"></textarea></b></font></p>
    <p><font size="3"><b><input type="submit" value="Send" name="send" style="font-family: Arial; font-size: 12pt; font-weight: bold"></b></font></p>
    <input type="hidden" name="state" value="1">
  </form>
  <b><font face="Arial" size="4" color="#e00000"><?php echo($announce)?></font></b><br><br>

</font>
</td></tr>
</table> 
</div>


</body>
</html>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
maeltarCommented:
I'd suggest using jQuery to do your form validation, it is incrediby simple to use with the jQuery Validation plugin : http://bassistance.de/jquery-plugins/jquery-plugin-validation/

I have scribbled this up in notpad and not tested am afriad, but the logic is correct, the imp[ort part to define the fields you want validating is the form field class, this must be set to required, more documentation on this is :

http://docs.jquery.com/Plugins/Validation

<html>
<head>

<!-- Get the validation jQuery plugin from http://bassistance.de/jquery-plugins/jquery-plugin-validation/ -->

<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<!-- Change this line to the required path -->
<script type="text/javascript" src="includes/js/jquery.validate.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){


// change this to the form name you require validating
$('#myFormName').validate();

});

</script>


<form method="post" action="<? echo $_SERVER['PHP_SELF']; ?>" name="myFormName">
<div style="width:400px"><fieldset><legend>My From</legend>
<p style="margin-left 50px"><label>Input Text Field 1</label><input type="text" name="field1" id="field1" class="required"></p>
<p style="margin-left 50px"><label>Input E-Mail Field</label><input type="text" name="fieldEmail" id="fieldEmail" class="required email"></p>
<p style="margin-left:100px"><input type="submit" name="myFormSubmit" id="myFormSubmit" value="Submit NOW"</p>
</fieldset>
</form>
</div>
</body>
</html>

Open in new window

0
maeltarCommented:
I have made a mistake on the form, it is the form id that needs to be set as well :

Line 16 should read ..

// change this to the form ID you require validating

Line 24 should read :

<form method="post" action="<? echo $_SERVER['PHP_SELF']; ?>" id="myFormName" name="myFormName">

Open in new window

0
HidesignAuthor Commented:
DaveBaldwin:- thanks. The form works. I had a few questions. Right now only the message fiekd is displaying in the email. How do I include all the fields. Also the mail header is appearing on the top of the form once it is submitted. Can I take this out.  Thanks
0
Dave BaldwinFixer of ProblemsCommented:
The PHP section from lines 88 to 92 is the part that displays the message and the header after it is sent.  You can take them out.  Because of the way that 'mail()' works, everything that is in the message body must be put in $msgText.  Starting at line 25, you can see how I create the '$header' and add things to it.  You can do the same with the $msgText if you want.  If you want a different format, you have to create a variable to hold the email message and add the fields to it.  If you do that, it will replace '$msgText' in the mail() statement.
0
HidesignAuthor Commented:
Thanks - worked great. Is there a way to have the form fields remain on the screen after the you hit send on the form. This way the person can see what they entered
0
Dave BaldwinFixer of ProblemsCommented:
There are several ways to do that but I think that should be a separate question.
0
Ray PaseurCommented:
This article only discusses checkboxes, but the code snippet illustrates a few of the important principles for dealing with external data.  While jQuery validation is great, it is really only a nicety for your client experience, and has nothing to do with the security validation -- that part must be done on the server after the client has transferred the data.  The article shows how to do that.  It also shows how to remember the client input.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_5450-Common-Sense-Examples-Using-Checkboxes-with-HTML-JavaScript-and-PHP.html

The code snippet also shows some of the design patterns you're looking for.  You can install it on your server and run it, or try it on my server here.
http://www.laprbass.com/RAY_form_highlight_errors.php

HTH, ~Ray
<?php // RAY_form_highlight_errors.php
error_reporting(E_ALL);


// DEMONSTRATE HOW TO HIGHLIGHT ERRORS IN FORM INPUT
// CLIENT IS ASKED TO PUT IN A VALUE
// IF THE VALUE FAILS OUR TEST WE SHOW AN ERROR MESSAGE
// WE PUT A MARKER NEXT TO THE INPUT CONTROL ON THE FORM
// WE TURN THE FORM BORDER RED
// SEE http://www.w3schools.com/CSS/pr_class_visibility.asp


// THESE CONDITIONS ARE SET FOR THE SCRIPT INITIALIZATION
$error_abc = 'hidden';
$boxer_abc = 'black';
$error_xyz = 'hidden';
$boxer_xyz = 'black';
$error_any = 'hidden';


// CAPTURE AND NORMALIZE THE POST VARIABLES - ADD YOUR OWN SANITY CHECKS HERE
$abc = (isset($_POST["abc"])) ? trim(strtoupper($_POST["abc"])) : NULL;
$xyz = (isset($_POST["xyz"])) ? trim(strtoupper($_POST["xyz"])) : NULL;

// IF ANYTHING WAS POSTED, VALIDATE IT
if (!empty($_POST))
{
    // VALIDATE THE 'abc' FIELD
    if ($abc != 'ABC')
    {
        $error_any = 'visible';
        $error_abc = 'visible';
        $boxer_abc = 'red';
        // $abc       = NULL;
    }

    // VALIDATE THE 'xyz' FIELD
    if ($xyz != 'XYZ')
    {
        $error_any = 'visible';
        $error_xyz = 'visible';
        $boxer_xyz = 'red';
        // $xyz       = NULL;
    }

    // DO WE HAVE INPUT FREE FROM ANY ERRORS?
    if ($error_any != 'visible')
    {
        echo "CONGRATULATIONS";
        die();
    }

    // OOPS - WE HAVE ERRORS
}

// IF NOTHING WAS POSTED, OR IF THERE ARE ERRORS, WE NEED NEW CLIENT INPUT
$form = <<<ENDFORM
<style type="text/css" media="all">
.error_any { visibility:$error_any; }
.error_abc { visibility:$error_abc; }
.error_xyz { visibility:$error_xyz; }
</style>
<pre>
<form method="post">
<span class="error_any">PLEASE CORRECT THE FOLLOWING ERRORS</span>
<span class="error_abc">YOU MUST ENTER 'abc' IN THIS FIELD</span>
PLEASE ENTER "ABC" HERE: <input style="border-color:$boxer_abc;" name="abc" value="$abc" />
<span class="error_xyz">YOU MUST ENTER 'xyz' IN THIS FIELD</span>
PLEASE ENTER "XYZ" HERE: <input style="border-color:$boxer_xyz;" name="xyz" value="$xyz" />
<input type="submit" />
</form>
ENDFORM;

// WRITE THE FORM WITH THE APPROPRIATE CSS STYLES ON THE ERROR MESSAGE FIELDS
echo $form;

Open in new window

0
HidesignAuthor Commented:
Thanks for all your help
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Scripting Languages

From novice to tech pro — start learning today.