I am hung up on an issue. I've got an html form, nothing fancy. On submission I need to verify the values submitted and if they fail I need to go back to the form and point out the error. I've done this many times before but with simple data verification like blank input fields or email address formatting. There is a lot of validation here and when I return to my form all the previous input it lost.
Here's what I have so far (some things may be currently missing as I am constantly tweaking it but you'll get the idea)
index.php
<div id="tabs-2">
<center><h1>Add Event Form:</h2></center>
<form name="htmlform" method="POST" action="htmlform.php">
<table>
<tr>
<td class="left"><label for="first_name">Event Name *</label></td>
<td><span><input type="text" name="event_name" value="<?PHP if(isset($_POST['event_name'])) echo htmlspecialchars($_POST['event_name']); ?>" required /></span></td>
</tr>
<tr>
<td class="left"><label for="first_name">Event Date *</label></td>
<td><span><input id="datepicker" type="text" name="event_date" value="<?PHP if(isset($_POST['event_date'])) echo htmlspecialchars($_POST['event_date']); ?>" required /></span></td>
</tr>
<tr>
<td class="left"><label for="first_name">Start Time *</label></td>
<td>
<span>
<select name="start_time" value="<?PHP if(isset($_POST['start_time'])) echo ($_POST['start_time']); ?>" required />
<?php
foreach($times as $time){
echo '<option value="' . $time . '">' . $time . '</option>';
}
?>
</span>
</td>
</tr>
<tr>
<td class="left"><label for="first_name" >End Time *</label></td>
<td>
<span>
<select name="end_time" value="<?PHP if(isset($_POST['end_time'])) echo ($_POST['end_time']); ?>" required />
<?php
foreach($times as $time){
echo '<option value="' . $time . '">' . $time . '</option>';
}
?>
</span>
</td>
</tr>
<tr>
<td class="left"><label for="first_name">Venue Name *</label></td>
<td><span><input type="text" name="venue_name" value="<?PHP if(isset($_POST['venue_name'])) echo htmlspecialchars($_POST['venue_name']); ?>" required /></span></td>
</tr>
<tr>
<td class="left"><label for="first_name">Venue Address *</label></td>
<td><span><input type="text" name="venue_address" value="<?PHP if(isset($_POST['venue_address'])) echo htmlspecialchars($_POST['venue_address']); ?>" required /></span></td>
</tr>
<tr>
<td class="left"><label for="first_name">Description</label></td>
<td><span><textarea name="description" style="height: 150px; font-size: 13px;" value="<?PHP if(isset($_POST['description'])) echo htmlspecialchars($_POST['description']); ?>" required ></textarea></span></td>
</tr>
<tr>
<td class="left"><label for="first_name">Event URL *</label></td>
<td><span><input type="text" name="event_url" value="<?PHP if(isset($_POST['event_url'])) echo htmlspecialchars($_POST['event_url']); ?>" required /></span></td>
</tr>
<tr>
<td class="left"><label for="first_name">Event Image URL *</label></td>
<td><span><input type="text" name="event_image" value="<?PHP if(isset($_POST['event_image'])) echo htmlspecialchars($_POST['event_image']); ?>" required /></span></td>
</tr>
</table>
<p><input class="eventSub" type="submit" name="form_submit" value="Submit"></p>
<br/>
</form>
</div>
and htmlform.php
<?php
$event_name = $_POST['event_name'];
$event_date = $_POST['event_date'];
$start_time = $_POST['start_time'];
$end_time = $_POST['end_time'];
$venue_name = $_POST['venue_name'];
$venue_address = $_POST['venue_address'];
$description = $_POST['description'];
$event_url = filter_var($_POST['event_url'], FILTER_SANITIZE_URL);
$event_image = filter_var($_POST['event_image'], FILTER_SANITIZE_URL);
$start = strtotime($start_time);
$end = strtotime($end_time);
if (filter_var($event_url, FILTER_VALIDATE_URL) === false) {
//die(header("location:index.php?error=true&reason=url#tabs-2"));
}
if (filter_var($event_image, FILTER_VALIDATE_URL) === false) {
//die(header("location:index.php?error=true&reason=url#tabs-2"));
}
if ($end < $start){
$next_day_format = strtotime("+1 day", strtotime($event_date));
$next_day = date("Y-m-d", $next_day_format);
$json_start_time = $event_date . "T" . $start_time;
$json_end_time = $next_day . "T" . $end_time;
}
else {
$json_start_time = $event_date . "T" . $start_time;
$json_end_time = $event_date . "T" . $end_time;
}
$cityclean = str_replace (" ", "+", $venue_address);
$fullurl = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $cityclean . "&sensor=true";
$string = file_get_contents($fullurl);
$params = json_decode($string, true);
$lon = $params['results'][0]['geometry']['location']['lng'];
$address = substr($params['results'][0]['formatted_address'],0,-5);
$lat = $params['results'][0]['geometry']['location']['lat'];
$address_array = explode(',',$address);
$state_zip = trim($address_array[2]);
$sz_array = explode(' ',$state_zip);
$state = $sz_array[0];
$city = trim($address_array[1]);
$zip = $sz_array[1];
?>
It's not quite finished yet. The ideal situation will send the submit to a json formated string once all fields are validated.
The question is if anything fails validation I would like to reload the previous page which the form was submitted but retain all entered values, as of now when it errors out and reloads the page, the form is blank.
The best way you could could get this done is to use Ajax.
1). As soon as the submit button is clicked, submit all values via Ajax to the php file, and get the result from the php file.
2). If php generated errors, then show the required error.
3). If php didn't generate any error, trigger
the form and it will be submitted.
Here's some quick code for you.
<script>
$("#form_submit").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "yourBackendFile.phps"
data: $('#form').serialize(); //add an 'id' attribute to your form with id = "form"
}).done(function( msg ) {
if(msg == 1)
{
//echo 1 from the php script if everything's fine.
$("#form").trigger("submit"); //submit the form now
}
else
{
//show the 'msg' somewhere. Now this msg would contain all the errors that the php generated.
}
});
});
</script>
UPDATE:
Didn't know why this stumped me so long, this is how I accomplished exactly what I was trying to do.
functions.php
<?php
$event_name = $event_date = $start_time = $end_time = $venue_name = $venue_address = $description = $event_url = $event_image = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//Checks if Event Name has been set
if(empty($_POST['event_name'])){
$error = 1;
$event_name_error_message = "Event Name Required";
}
else { $event_name = $_POST['event_name']; }
//Checks if an Event Date has been selected
if(empty($_POST['event_date'])) {
$error = 1;
$event_date_error_message = "Event Date Required";
}
else { $event_date = $_POST['event_date']; }
//Checks if a Venue Name has been set
if(empty($_POST['venue_name'])) {
$error = 1;
$venue_name_error_message = "Venue Name Required";
}
else { $venue_name = $_POST['venue_name']; }
//Checks if a Start Time has been selected
if(empty($_POST['start_time'])) {
$error = 1;
$start_time_error = "Start Time Required";
}
else { $start_time = $_POST['start_time']; }
//Checks if an End Time has been selected
if(empty($_POST['end_time'])) {
$error = 1;
$end_time_error = "End Time Required";
}
else { $end_time = $_POST['end_time']; }
//Checks if the Venue Address has been entered
if(empty($_POST['venue_address'])) {
$error = 1;
$venue_address_error_message = "Venue Address Required";
}
else { $venue_address = $_POST['venue_address']; }
//Checks if a Description has been entered
if(empty($_POST['description'])) {
$error = 1;
$description_error_message = "Event Description Required";
}
else { $description = $_POST['description']; }
//Check if an event URL has been entered. Second condition checks if the URL is properly formated
if(empty($_POST['event_url'])) {
$event_url_error = "URL Required";
$error = 1;
}
else {
$event_url = filter_var($_POST['event_url'], FILTER_SANITIZE_URL);
if (filter_var($event_url, FILTER_VALIDATE_URL) === false) {
$event_url_error = "Event URL not properly formatted!";
$error = 1;
}
}
//Check if an event image URL has been entered. Second condition checks if the URL is properly formated
if(empty($_POST['event_image'])) {
$event_image_error = "URL Required";
$error = 1;
}
else {
$event_image = filter_var($_POST['event_image'], FILTER_SANITIZE_URL);
if (filter_var($event_image, FILTER_VALIDATE_URL) === false) {
$event_image_error = "Event Image URL not properly formatted!";
$error = 1;
}
}
//Sets the end date to the following day if the end date time stamp is less than the start, assumes that an event which starts at 20:00 and ends at 02:00 has gone into the next day
if(!isset($error)){
//Converts the time stamps to a number which can be calculated
$start_time = $_POST['start_time'];
$end_time = $_POST['end_time'];
$start = strtotime($start_time);
$end = strtotime($end_time);
if ($end < $start or $end == $start){
$next_day_format = strtotime("+1 day", strtotime($event_date));
$next_day = date("Y-m-d", $next_day_format);
$json_start_time = $event_date . "T" . $start_time;
$json_end_time = $next_day . "T" . $end_time;
}
else {
$json_start_time = $event_date . "T" . $start_time;
$json_end_time = $event_date . "T" . $end_time;
}
//Fills in missing info from the google map api so that a pin can be placed on the map for the event
$cityclean = str_replace (" ", "+", $venue_address);
$fullurl = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $cityclean . "&sensor=true";
$string = file_get_contents($fullurl);
$params = json_decode($string, true);
$lon = $params['results'][0]['geometry']['location']['lng'];
$address = substr($params['results'][0]['formatted_address'],0,-5);
$lat = $params['results'][0]['geometry']['location']['lat'];
$address_array = explode(',',$address);
$state_zip = trim($address_array[2]);
$sz_array = explode(' ',$state_zip);
$state = $sz_array[0];
$city = trim($address_array[1]);
$zip = $sz_array[1];
echo "Lon - $lon<br/>";
echo "Name - $event_name<br/>";
echo "State - $state<br/>";
echo "Address - $address<br/>";
echo "Lat - $lat<br/>";
echo "City - $city<br/>";
echo "Zip - $zip<br/>";
echo "URL - $event_url<br/>";
echo "Image URL - $event_image<br/>";
echo "Start Time - $start_time<br/>";
echo "End Time - $end_time<br/>";
//Builds the completed json string which will then be submitted to the ant target
$complete_json_string = '{"results":[{"venue":{"lon":"' . $lon . '","name":"' . $venue_name . '","state":"' . $state . '","address":"' . $address .'","lat":"' . $lat . '","city":"' . $city . '","zip":"' . $zip . '"},"start_time":"' . $json_start_time . '","end_time":"' . $json_end_time . '","event_url":"' . $event_url . '","description":"' . $description . '","name":"' . $event_name . '","image_url":"' . $event_image . '"}]}';
echo $complete_json_string;
}
}
if (empty($_POST["comment"])) { $comment = ""; }
else {
$cleaned = test_input($_POST["comment"]);
$comment = ($_POST["comment"]);
}
function test_input($data) {
$data = trim($data);
$data = addslashes($data);
return $data;
}
$times=ARRAY('00:00:00','00:15:00','00:30:00','00:45:00','01:00:00','01:15:00','01:30:00','01:45:00','02:00:00','02:15:00','02:30:00','02:45:00','03:00:00','03:15:00','03:30:00','03:45:00','04:00:00','04:15:00','04:30:00','04:45:00','05:00:00','05:15:00','05:30:00','05:45:00','06:00:00','06:15:00','06:30:00','06:45:00','07:00:00','07:15:00','07:30:00','07:45:00','08:00:00','08:15:00','08:30:00','08:45:00','09:00:00','09:15:00','09:30:00','09:45:00','10:00:00','10:15:00','10:30:00','10:45:00','11:00:00','11:15:00','11:30:00','11:45:00','12:00:00','12:15:00','12:30:00','12:45:00','13:00:00','13:15:00','13:30:00','13:45:00','14:00:00','14:15:00','14:30:00','14:45:00','15:00:00','15:15:00','15:30:00','15:45:00','16:00:00','16:15:00','16:30:00','16:45:00','17:00:00','17:15:00','17:30:00','17:45:00','18:00:00','18:15:00','18:30:00','18:45:00','19:00:00','19:15:00','19:30:00','19:45:00','20:00:00','20:15:00','20:30:00','20:45:00','21:00:00','21:15:00','21:30:00','21:45:00','22:00:00','22:15:00','22:30:00','22:45:00','23:00:00','23:15:00','23:30:00','23:45:00','24:00:00');
session_start();
?>
index.php
<?php require('scripts/functions.php');?>
<html>
<head>
<link rel="stylesheet" href="css/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="css/style.css"/>
<script src="scripts/jquery.js"></script>
<script src="scripts/jquery-ui.js"></script>
<script language="javascript">
function clearform() {
document.getElementById("json").value="";
}
</script>
<script>
$(function() {
$( "#tabs" ).tabs();
});
$(function() {
$( "#datepicker" ).datepicker({ dateFormat: 'yy-mm-dd' });
});
</script>
<title>Add Manual Event Data</title>
</head>
<body>
<div id="tabs" class="body-check">
<ul>
<li><a href="#tabs-1">Event By String</a></li>
<li><a href="#tabs-2">Add Event Form</a></li>
</ul>
<div id="tabs-1">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<center><h1>Add Event Data:</h1></center>
<p>
<textarea id="json" name="comment"><?php echo $comment;?></textarea>
</p>
<input type="submit" name="submit" value="Submit">
</form>
<?php
if (isset($cleaned)){
$_SESSION['json_string'] = $cleaned;
echo '<div id="ant"><iframe src="scripts/ant.php"></iframe></div>';
}
?>
</div>
<div id="tabs-2">
<center><h1>Add Event Form:</h2></center>
<form name="htmlform" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) . "#tabs-2";?>">
<table>
<tr>
<td class="left"><label for="first_name">Event Name *</label></td>
<td><span><input type="text" name="event_name" value="<?PHP if(isset($_POST['event_name'])) echo htmlspecialchars($_POST['event_name']); ?>" />
<?php if(isset($event_name_error_message)) echo "<span class='error'>$event_name_error_message</span>"; ?>
</span></td>
</tr>
<tr>
<td class="left"><label for="first_name">Event Date *</label></td>
<td><span><input id="datepicker" type="text" name="event_date" value="<?PHP if(isset($_POST['event_date'])) echo htmlspecialchars($_POST['event_date']); ?>" />
<?php if(isset($event_date_error_message)) echo "<span class='error'>$event_date_error_message</span>"; ?>
</span></td>
</tr>
<tr>
<td class="left"><label for="first_name">Start Time *</label></td>
<td>
<span>
<select name="start_time">
<option value="<?php echo $start_time;?>"><?php if(isset($_POST['start_time'])) { echo htmlspecialchars($_POST['start_time']); }?></option>
<?php
foreach($times as $time){
echo '<option value="' . $time . '">' . $time . '</option>';
}
?>
</select>
<?php if(isset($start_time_error)) echo "<span class='error'>$start_time_error</span>"; ?>
</span>
</td>
</tr>
<tr>
<td class="left"><label for="first_name" >End Time *</label></td>
<td>
<span>
<select name="end_time">
<option value="<?php echo $end_time; ?>"><?PHP if(isset($_POST['end_time'])) { echo htmlspecialchars($_POST['end_time']); } ?></option>
<?php
foreach($times as $time){
echo '<option value="' . $time . '">' . $time . '</option>';
}
?>
</select>
<?php if(isset($end_time_error)) echo "<span class='error'>$end_time_error</span>"; ?>
</span>
</td>
</tr>
<tr>
<td class="left"><label for="first_name">Venue Name *</label></td>
<td><span><input type="text" name="venue_name" value="<?PHP if(isset($_POST['venue_name'])) echo htmlspecialchars($_POST['venue_name']); ?>" />
<?php if(isset($venue_name_error_message)) echo "<span class='error'>$venue_name_error_message</span>"; ?>
</span></td>
</tr>
<tr>
<td class="left"><label for="first_name">Venue Address *</label></td>
<td><span><input type="text" name="venue_address" value="<?PHP if(isset($_POST['venue_address'])) echo htmlspecialchars($_POST['venue_address']); ?>" />
<?php if(isset($venue_address_error_message)) echo "<span class='error'>$venue_address_error_message</span>"; ?>
</span></td>
</tr>
<tr>
<td class="left"><label for="first_name">Description</label></td>
<td><span><textarea name="description" style="height: 150px; font-size: 13px;" ><?php if(isset($_POST['description'])) echo htmlspecialchars($_POST['description']); ?></textarea>
<?php if(isset($description_error_message)) echo "<span class='error'>$description_error_message</span>"; ?>
</span></td>
</tr>
<tr>
<td class="left"><label for="first_name">Event URL *</label></td>
<td><span><input type="text" name="event_url" value="<?php if(isset($_POST['event_url'])) echo htmlspecialchars($_POST['event_url']);?>" />
<?php if(isset($event_url_error)) echo "<span class='error'>$event_url_error</span>"; ?>
</span></td>
</tr>
<tr>
<td class="left"><label for="first_name">Event Image URL *</label></td>
<td><span><input type="text" name="event_image" value="<?PHP if(isset($_POST['event_image'])) echo htmlspecialchars($_POST['event_image']); ?>" />
<?php if(isset($event_image_error)) echo "<span class='error'>$event_image_error</span>"; ?>
</span></td>
</tr>
</table>
<p><input class="eventSub" type="submit" name="form_submit" value="Submit"></p>
<br/>
</form>
</div>
</div>
</body>
</html>
That way my code and index are separated. Thanks again.
It looks like the problem is that the form action is htmlform.php, so when you submit the form you are posting to that PHP file. This means that your PHP in index.php that tries to echo these variables (e.g. echo htmlspecialchars($_POST['event_name']
), simply doesn't have access to them.
You have a couple of options
- You could move the form handing logic out of htmlform.php into index.php. Then you have access to the
$_POST
array for repopulating the form fields as well as showing an error.
- You could use AJAX to post the values from your form fields in index.php to htmlform.php, and then parse the reponse (probably using JSON) to add error messages by your form fields whilst still retaining the user's input. There are lots of useful tutorials on the web to help you do this.