In the last section, we added a feature to the server so that it can accept POST requests to create a new item on the site. We will now allow our client to take advantage of that feature.
First, we add an input form to the HTML of our client page:
<h1>Add an item</h1>
<table>
<tr>
<td>Title:</td>
<td><input id='add_title'></input></td>
</tr>
<tr>
<td>Description:</td>
<td><input id='add_description'></input></td>
</tr>
<tr>
<td>Reserve:</td>
<td><input id='add_reserve'></input></td>
</tr>
</table>
<button onclick='add_item();'>Create new item</button>
Now we have to create the add_item method. Fortunately, on the client side this is easier than the GET method, as we don’t have to parse any input data – we can just get it straight from the page. Within the <script> tags in the page, add the following function:
function add_item()
{
var request = get_request_object();
We first get hold of the three entry fields:
var title_field = document.getElementById("add_title");
var description_field = document.getElementById("add_description");
var reserve_field = document.getElementById("add_reserve");
Then we construct a request containing the data we want to send to the server. We use our simple data format, as always:
// Set up the request data
var content = "";
content += "title:" + title_field.value + "\n";
content += "description:" + description_field.value + "\n";
content += "reserve_field:" + reserve_field.value + "\n";
Finally, we can post the request to the server:
// Set up the request
request.open("POST", "http://localhost:8080/auction/item", true);
// Send the request
request.send(content);
}
Save your new client page, reload it in your browser, and try adding a new item to the server:
Title: Bike Description: Has a saddle, a bell that rings, and things to make it look good. Reserve: 15.00
Use the “View all items” button to see if your item actually got added.
Note that as currently written, there’s no user feedback at all to indicate that the item was added successfully. You could add some feedback to the application by giving your POST request an onreadystatechange handler to put a marker or message into the page to show whether the request succeeded or failed. You could also do things like update the list of items, if it’s currently shown, and clear the entry fields. For this last, note that the value property of the entry fields is read/write – you could just set them to the empty string when the request succeeds.
Our next section is probably the easiest to implement: Deleting an item from the database.
Valid XHTML | Copyright | Last Modified: 1/Apr/2009 |