CSS

Creating a simple to-do application – Part 2

Continuing on from last weeks tutorial (Creating a simple to-do application – Part 1) and the short snippet (Turning a form element into JSON and submiting it via jQuery ), this week we’ll be writing a PHP page to accept and process the form submit and return a JSON response.

Installing PHP on your web server

There are several ways to install PHP to your web server, but each is dependent on what web server you are running. The two main ones I will deal with are Microsoft’s Internet Information Services (IIS) and Apache. IIS will only run on Windows, but Apache will run on either Windows, OSX or your favorite Linux Distro (e.g Ubuntu). For each operating system there are several easy to use packages that will install and configure both the web server and php.

Apache

The easiest package for Apache I find is XAMPP, it provides installers for all of the major platforms and is very easy to use. You can download it directly from the site based on your operating system and follow their install guides.

The XAMPP site includes details on where to put your files and how to create alias folders. These topics and more are covered in the install guides above.

IIS

IIS actually comes free with Windows, it generally isn’t installed by default but you can add it in the “Add/Remove Programs” section of the Control Panel under “Turn On/Off Windows Features” (For a detailed step by step guide, click here). The easiest way to install PHP is to download the Microsoft Web Platform Installer. It will offer you a range of programs to install, everything from PHP and WordPress to various e-commerce platforms. All you do is pick the applications you want, and they will automatically be installed!

By default web files go in the following folder C:\inetpub\wwwroot, you can however create “Virtual Folders” that point anywhere you want. To continue this tutorial, please save the index.html page in to wwwroot or create a virtual folder

Getting started

Assuming you’ve gotten your web server running and PHP configured, let’s get started! (If you are having trouble, please feel free to ask in the comments section below and I will help as best I can).

First we’ll create our submit.php file (in the same folder as our index.html file) and then using the PHP global variable $_POST we will retrieve the form values we have submitted using jQuery.
PHP code is always wrapped in “<?php ?>” tags, anything outside of these tags is rendered as normal (like HTML).

<?php
$name = $_POST["new-task-name"];
$date = $_POST["new-task-date"];
$desc = $_POST["new-task-desc"];
$email = $_POST["new-task-email"];
$priority = $_POST["new-task-priority"];
$color = $_POST["new-task-color"];
?>

We are using the $_POST variable instead of the $_GET because we specified our jQuery submit method as ‘POST’, this can be easily changed if you prefer to use ‘GET’

Now that we have our form values, we’ll have to provide some basic validation on them. We know that we need a name, the date and priority values, but we also know that we can specify optional values and in the case of the email field a comma separated list. First we’ll make sure our required values, do in fact have values and that they are formatted correctly.

Firstly, we’re going to specify some default values and then update the variables after we have confirmed that each of the form values has been provided. We can do this using the empty function.

<?php
$name = null;
$date = date('c');
$desc = null;
$email = null;
$priority = 2;
$color = '#ffffff';

if (!empty($_POST["new-task-name"]))
    $name = $_POST["new-task-name"];
if (!empty($_POST["new-task-date"]))
    $date = $_POST["new-task-date"];
if (!empty($_POST["new-task-desc"]))
    $desc = $_POST["new-task-desc"];
if (!empty($_POST["new-task-email"]))
    $email = $_POST["new-task-email"];
if (!empty($_POST["new-task-priority"]))
    $priority = $_POST["new-task-priority"];
if (!empty($_POST["new-task-color"]))
    $color = $_POST["new-task-color"];
?>

We’re also going to confirm that the date value is in the correct format and that the priority is an integer value. We do this using the DateTime and intval functions. Using the explode and implode functions we can also convert the comma separated email list into an array and back to a string.

<?php
$name = null;
$date = date('c');
$desc = null;
$email = null;
$priority = 2;
$color = '#ffffff';

if (!empty($_POST["new-task-name"]))
    $name = $_POST["new-task-name"];
if (!empty($_POST["new-task-date"]))
    $date = new DateTime($_POST["new-task-date"]);
if (!empty($_POST["new-task-desc"]))
    $desc = $_POST["new-task-desc"];
if (!empty($_POST["new-task-email"]))
    $email = explode(',', $_POST["new-task-email"]);
if (!empty($_POST["new-task-priority"]))
    $priority = intval($_POST["new-task-priority"]);
if (!empty($_POST["new-task-color"]))
    $color = $_POST["new-task-color"];
?>

We must also provide feedback to the user if the required values are not set. To do this we will return a JSON object with a success value of false, we’ll also return a list of messages informing the user of what they need to do. Using the json_encode function we can convert our $result array to JSON very easily

<?php
$name = null;
$date = date('c');
$desc = null;
$email = null;
$priority = 2;
$color = '#ffffff';

$result = array();
$result['error'] = array();

if (!empty($_POST["new-task-name"]))
    $name = $_POST["new-task-name"];
else 
    array_push($result['error'], 'Please specify a name for your task');

if (!empty($_POST["new-task-date"]))
    $date = new DateTime($_POST["new-task-date"]);
else 
    array_push($result['error'], 'Please specify a date for your task');

if (!empty($_POST["new-task-desc"]))
    $desc = $_POST["new-task-desc"];

if (!empty($_POST["new-task-email"]))
    $email = explode(',', $_POST["new-task-email"]);

if (!empty($_POST["new-task-priority"]))
    $priority = intval($_POST["new-task-priority"]);
else 
    array_push($result['error'], 'Please specify a valid priority for your task');

if (!empty($_POST["new-task-color"]))
    $color = $_POST["new-task-color"];

if(isset($result['error']) && count($result['error']) > 0){
    $result['success'] = false;
} else {
    $result['success'] = true;
    $result['name'] = $name;
    $result['date'] = $date->format('c');
    $result['desc'] = $desc;
    $result['email'] = implode(',', $email);
    $result['priority'] = $priority;
    $result['color'] = $color;
}

echo json_encode($result);
?>

We now have to update our jQuery submit method to handle the response and either show an error message or add the task row to the table.

$.ajax({
    type: "POST",
    url: "submit.php",
    data: json,
    dataType: "json"
}).success(function(state) { 
    if(state.success === true) {
        tbody.append('<tr><th scope="row" style="background-color:' + state['color'] + 
            '"><input type="checkbox" /></th><td>' + state['date'] +
            '</td><td>' + state['priority'] + '</td><td>' + state['name'] + 
            '</td><td>' + state['desc'] + '</td><td>' + state['email'] + '</td></tr>');    
    } else {
        alert(state.error.join());
    }
}).fail(function(state) { 
    alert("Failed to add to-do"); 
});

As you can see, if the success value of the state returned by out PHP file is true we add the row from the result. If it is false we append all of the error messages from the error array in to one string using the join function and display it using the alert function.

We have now validated and cleansed our form values, we have also started to add some more complex logic to our application (in the form of error messages).

Next week

Next week we’ll cover setting up a MySql database and creating some basic tables. We’ll also update our submit.php file to save the task to the database and add some more functionality to our application by converting out static HTML page to PHP and adding in some basic authentication. Security and file/database permissions deserve their own tutorial, so I will be covering them in depth very soon.

A battle hardened software developer with a mixed and colorful background, who can't come up with a decent author bio More articles by Jonathan Schnittger
Home CSS Deals DesignBombs HTML HTML5 JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress