Chapter 9. Handling JSON Data: Client, Meet Server

image with no caption

As useful as reading data from an XML file was, that won’t always cut the mustard. A more efficient data interchange format (JavaScript Object Notation, aka JSON) will make it easier to get data from the server side. JSON is easier to generate and read than XML, too. Using jQuery, PHP, and SQL, you’ll learn how to create a database to store information so you can retrieve it later, using JSON, and display it on the screen using jQuery. A true web application superpower!

From: Webville MegaCorps Marketing

Subject: Re: 42nd Annual Bit to Byte Race results page

Hey Web Design Team,

We really like the updates you’ve made to the website.

We have a problem though: nobody in our office knows XML! So we don’t know how to add new finishers to the race website.

We’ve tried, but every time we get it wrong, it makes the website do some strange things... Finishers don’t show, or fields disappear from the page even though they’re in the XML file. It’s very odd.

What we’d really like is some way to just type into a few boxes and click a button to add a finisher. Can you make this happen?

And if we make a mistake, can you make it so we don’t break the whole site?

I know it’s only three days until we all fly out to Hawaii, but we’d really like this working before we go. Do you think you can make it in time?

--

Dionah C. Housney

Head of Marketing

Webville MegaCorp

image with no caption

When there are errors in the XML, the logic that we wrote to read and parse that XML fails. These errors mainly happen when there are issues with the tags, like forgetting to close a tag or having the wrong case in the tag name. However, data in the tags can also cause XML some problems if it’s not encoded for use in XML properly.

image with no caption
image with no caption

Odds are, you’ve already thought of using an HTML form. With a form, you can collect all sorts of data and send it to the server for processing. Forms have several different types of elements used to collect various types of data. We’ll look at forms in much more detail in Chapter 10, but for now, let’s just use two of the most basic form elements: a text box and a drop-down list. You may be a pro at forms already, but let’s just take a quick look so we know what we’re dealing with here.

image with no caption
image with no caption

That should work and be easy to do, since we’ve already figured out how to add tabs.

Then we can work on how we’re going to store/retrieve that data to display in the Finishers lists.

Now we need to send the data collected by the form to the server and store it somehow. To do that, we’re going to use another language, PHP, to insert the data into a database. Don’t worry! We’ll get you up to speed on PHP and databases in a bit, but first let’s focus on how we get our form data to the server.

There are two methods of sending the data to the server using HTTP: GET and POST. The main difference between GET and POST is how the data is sent to the server. GET will append the form field names and values onto the end of the URL as key/value pairs. PHP can read this information out of an associative array called $_GET[], which is sent to the server when the form is submitted. The data is visible after the ? in the URL.

POST sends the data—also in an associative array, but encoded differently—and is not visible to the end user in the URL. The $_POST[] associative array contains all the information from the form elements. This, like the $_GET[] array, is a series of key/value pairs of the form element names and values.

image with no caption
image with no caption
image with no caption

Yes, the form could send the information...

But, like we mentioned about the benefits of jQuery and Ajax in the previous chapter, you don’t have to reload the entire page to get or send data, so the user won’t see the whole page reload each time. However, before you send the data to the server using jQuery and Ajax, you need to get it ready for sending.

Before we can send information to the server (using Ajax), we need to do a little prepping to get it into a format that the Ajax call can send and the server will understand. To do this, we serialize our data into a single object, so the Ajax call can send it as one single package. jQuery offers two form helper methods for serializing data: serialize and serializeArray. The former will join all the inputs of your form into a single string of key/value pairs, separated by ampersands (&). The latter will create an associative array of key/value pairs, which is still a single object but is much more structured than the result of the simple serialize method. We’ll take a look at both, but we’re going to use serializeArray for our marathon data.

image with no caption
image with no caption

jQuery provides a shortcut method, post, dedicated to sending data to the server. The post method takes several parameters, including the URL you want to send your information to, the information you want to send, and a handler function that will run when the POST is complete.

image with no caption

Relational Database Management Systems (RDBMS) are extremely organized applications designed to store, organize, and remember relationships between your various pieces of data.

Often called database servers, they come in various shapes and sizes (and costs). For our purposes, we’ll use a free database server called MySQL. You communicate with a database server in a language it can understand, which in our case is SQL. A database server typically runs alongside a web server, sometimes on the same server, and they work in concert to read and write data and deliver web pages.

image with no caption

MySQL databases are organized into tables, which store information as rows and columns of related data. Most web applications use one or more tables inside a single database, sort of like different file folders within a file cabinet.

image with no caption
image with no caption
image with no caption

There is one primary way of putting data into our database, another way to change/update it, and a third to get it back out again. We’ll look at getting data out in a bit, but for now, let’s focus on putting data into our database tables.

To put data into database tables, we use an insert statement.

image with no caption

insert statements allow you to put information into a single table. They are mostly used to insert one record at a time, but some advanced SQL users can create insert statements that add multiple rows to the table. For our purposes, however, we’ll stick to the one-at-a-time syntax.

It’s recommended that you specify the columns in the order you want to insert your data, although it’s not necessary. Not specifying the columns can lead to data issues, since it will automatically put the first value in the first column, the second value in the second column, etc. You’ll need very intimate knowledge of your data tables to be confident of using this method.

PHP is a programming language, and it needs an environment to run in: a web server with PHP support. PHP scripts and web pages that rely on the scripts must be placed on a real web server, as opposed to just opening a script directly from a local filesystem.

Web browsers know nothing about PHP and, therefore, have no ability to run PHP scripts.

image with no caption
image with no caption

Web servers with PHP support are equipped to run PHP scripts and turn them into HTML web pages that browsers can understand.

image with no caption

There will be jQuery, we promise.

But first, let’s look at how we get our PHP file to handle POST data, too, so it can write it into the database. We’ll also look at some of the important things to remember when dealing with sending information to your server.

We’ve already looked at the special object created to handle the transportation of information from the form in the browser to the server: the $_POST object. It’s an associative array of all the information you sent, using the name (not the IDs) of the HTML elements as the key for the associative array, and the information in the HTML element as the value of the associative array. The PHP code on the server reads the $_POST object and determines what information has been sent to the server.

You can get the information back out of this array by using the key you sent with it (the name of the HTML element). This will return the value in your PHP script.

image with no caption
image with no caption

We’re almost at the point where we can grab the data back out of the database and figure out how to display it in our Finishers lists. But first, we need a little more PHP to get us connected to the database...

Remember how when you went through the PHP installation process, you selected a particular library near the end of the process?

image with no caption

This library will enable PHP to talk to the MySQL database. We’ll use this library to connect to the database we’ve created so we can start reading out the runner data.

image with no caption

To read data from databases, we use a select statement, and the data is returned in a resultset. The resultset is a collection of all the data you asked for in your select query. Using a select statement, you can also join several tables, so you can get data from more than one table in the same resultset.

image with no caption

Up to now, we’ve looked at some very basic PHP and some not-so-basic PHP. We’ve seen how to write some basic information to the screen and how to connect to a database and write a select statement to get information out of a database. Now let’s see how we can get information from a database and write that information to the screen.

JSON, short for JavaScript Object Notation, is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. That’s what makes it perfect for structuring and transferring data. It’s based on a subset of the standard used to define JavaScript, and is language independent. That means it can be used with pretty much any programming language. It is more efficient at transferring data than XML, and is based on name/value pairs, like associative arrays. The values in JSON can be strings, numbers, arrays, objects, Boolean values (true or false) or null.

image with no caption

To access the information in the JSON object, you can use the same notation that you do for any other object: the dot (.) notation. Arrays inside the JSON object are like other JavaScript arrays and have the same properties, like length. In our example JSON object above, you would find out how many books were returned by using books.book.length. Different JSON objects will have different structures, so you might not need as many dots to access the array object.

Since JSON is so prevalent and easy to use, the good folks at jQuery built a special shortcut just for dealing with getting JSON data: the getJSON method.

image with no caption

If this seems familiar, that’s because it’s almost the same as the post method we used earlier to get the data from the form. This simple method is a shortcut for the ajax method, with several parameters already set for you. To make this call without the shortcut, it would look like this:

image with no caption

Yes, we can.

As luck would have it, the PHP folks thought of this already. Let’s have a look at a few more PHP basics, and then see how to combine those with other PHP functions to get our data in JSON.

Let’s face it, nobody really likes a bunch of coding rules, but there are just a few more things about PHP—much of which are syntax—that we should take a look at to help you wrangle your data for jQuery. Thankfully, we’ve already seen many of these concepts in relation to JavaScript, so we’ll keep this as quick and painless as possible...

There are a few more rules that will help us get the data we need, format it correctly, and get it onto our web pages.

OK, now that we’ve got that out of the way, let’s see what PHP can do for us! The json_encode function in PHP allows you to take an associative array and convert it into a JSON-encoded string of values.

image with no caption

But before we can encode the data, it must be in a single associative array. We’ve already seen a method to loop through the resultset and see each associative array in there. What we need is a way to take each of these arrays and combine them into a single one. Using the PHP function array_push, we can add new items onto the end of an array.

image with no caption

The json_encode function in PHP allows us to convert an associative array into a JSON-encoded string of values. These values can then be accessed in JavaScript as associative arrays too, so we can loop through them and interact with them in the same way we interact with other arrays.

When we were using XML, we had to scan through the data to find the next runner. Then, once we found a runner, we again had to find if the runner was male or female. Remember that JSON object that gets returned from json_encode? With the JSON object, we can directly access its properties, using the dot (.) notation. It contains a single array, called runners, as a property. And, once we have the array, we can use the key of the associative array to know if the runner is male or female—which is much more efficient than looking for it each time.

With the increase of spam bots and hackers trying to get ownership of your dataset for nefarious purposes, you should never trust the data that is entered into a web form. It’s always a good idea to validate and sanitize any data sent to your server before you insert it into your database. This ensures that you got the type of data you expected for a particular field (validation) and that the data you received doesn’t contain anything that could be potentially dangerous to your server or database (sanitization). This can help protect you against issues like SQL injections, drive-by cross-site scripting issues, and lots of other nasty things you can find out more about online. For our application, we’ll use some nifty PHP methods to clean up our data and make sure the correct data is used.

image with no caption

There are many other functions you could also look at for data sanitization; these include htmlentities, trim, stripslashes, mysql_real_escape_string, and many more. You can find a bunch more of these in Chapter 6 of Head First PHP & MySQL.

Use the same PHP file for multiple purposes

We’ve looked at the two ways of sending data to the server to be processed by PHP: POST and GET. In combination with some conditional logic, we can detect if there was a POST or a GET request to our PHP file and act accordingly. Remember that hidden field we added to our form a few pages ago?

<input type="hidden" name="action" value="addRunner" id="action">

We can watch for this value in the POST, and know that we posted a form. Then, we can run some data validation and sanitization functions to make sure we got all the data we want. Similarly, if we update the getJSON call to get the runners from the database with a URL parameter (for the $_GET PHP object), we can target just that code in the PHP file to run. That way, we’ll only have one PHP file to maintain.

image with no caption
image with no caption
image with no caption

Do this!

Update the getJSON call to include a URL parameter called action with a value of getRunners to tell the service.php file to return the runners.

You’ve got Chapter 9 under your belt, and now you’ve added some basic PHP, MySQL, JSON, and more Ajax to your toolbox.