Java Reference
In-Depth Information
Sending Information
We can also use Ajax to send information, usually as a JSON string. Back in Chapter 8 , we
created a form for entering information about a superhero. When the form was submitted
the data was converted into a JSON string, which was then shown in an alert dialog. Using
Ajax, this string could be saved to a database or sent to an external web API for processing.
Unfortunately, we're without a database to save this information to, but there's a very handy
website that can be used for testing Ajax requests and responses, called Reqres. It will ac-
cept a request containing JSON data and return a response that mimics making a save to a
database, although it doesn't actually save any of the data that you send. We'll use it here to
demonstrate the techniques.
The main difference when sending information is that the open() method's first argument
needs to be the HTTP POST method, and the JSON string will be provided as an argument
to the send() method.
To implement this in our superhero form example, all we do is change the last line of the
makeHero() function from:
scripts.js (excerpt)
Now we add the send() function to the scripts.js file:
scripts.js (excerpt)
function send(hero) {
var xhr = new XMLHttpRequest();"POST", "", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function(){
if (xhr.readyState === 4 && xhr.status === 201) {
Search WWH ::

Custom Search