Using Ajax, you can now save orders to the server and retrieve orders from the server. The last thing to do is to delete orders from the server when they are delivered.
To do this, you will send an HTTP request to the URL for an individual order. As you did with RemoteDataStore.prototype.get, you will use the server URL, but you will append a slash and the customer’s email address.
You will be
sending the server a DELETE
request.
DELETE
is one of the HTTP verbs. The
server knows to remove the data associated with that customer’s
email address if it receives a DELETE
request
at that URL.
jQuery provides the $.get and
$.post methods as a convenience because these
are the two most common HTTP verbs used. For example, a
GET
request is used whenever the browser asks
for an HTML, CSS, JavaScript, or image file (among others). A
POST
request is used most often when a form
is submitted.
jQuery does not provide a convenience method for sending
DELETE
requests via Ajax. Instead, you will
need to use the $.ajax method.
($.get and $.post actually
call $.ajax for you, specifying
GET
and POST
as the HTTP
verbs.)
In remotedatastore.js, add the
remove prototype method. In it, call the
$.ajax method, passing it two arguments.
The first argument is an individual coffee order’s URL, made up of
the server URL, a slash, and
the key (the customer’s email address).
The second argument is an object that contains the options,
or settings, for the Ajax request. The only option you need
to specify for the remove method
is that the type
is DELETE.
... RemoteDataStore.prototype.get = function (key, cb) { ... }; RemoteDataStore.prototype.remove = function (key) { $.ajax(this.serverUrl + '/' + key, { type: 'DELETE' }); }; App.RemoteDataStore = RemoteDataStore; window.App = App; ...
(There are many options available for Ajax requests, which you can read about at api.jquery.com/jquery.ajax.)
Save and return to the console. Instantiate a new RemoteDataStore and invoke the remove method. Pass it the email address for the test orders you have created. Finally, call getAll to confirm that it is no longer included in the orders returned from the server.
var remoteDS = new App.RemoteDataStore ("http://coffeerun-v2-rest-api.herokuapp.com/api/coffeeorders"); remoteDS.remove('[email protected]'); remoteDS.getAll();
If you inspect the response from the server for the
DELETE
request, you can see that the server
sends back information about what it did (Figure 13.11). (As we mentioned earlier,
other servers may provide different information in
the response.)
18.118.2.225