Eight Weeks of Prototype: Week 8, A Complete Prototype Example
Ajax Request Handler to Return Contacts
The next step is to write a PHP script that returns a list of the existing contacts in JSON format. This script will be requested by the JavaScript code we write later in the article.
Essentially, all this script needs to do is connect to the database, retrieve a list of contacts using the the getContacts() method of ContactManager, then sent it back as JSON data. The code used to achieve this is shown in Listing 5.
If you recall from the fifth article in this series, to send JSON data you send the application/json content-type header, then using json_encode() to convert a PHP variable to JSON data.
require_once('database.php'); require_once('ContactManager.php'); $cm = new ContactManager(); $json = $cm->getContacts(); header('Content-type: application/json'); echo json_encode($json);
In the fifth article in this series I also showed you how to detect if a HTTP request occurred using Ajax or using a "normal" request. You may wish to include such a check in this file just in case a user tries to access the file directly from in their browser.




