Ajax - csusbdt/322-2016 GitHub Wiki
- Add http message header Content-type: application/json from the server side.
- Redo videos.
Read about the JSON data representation format.
I reorganized this assignment so the videos do not correspond exactly to these instructions.
In the following 4 videos, I walk through the examples given below, which explain Ajax and a little bit of PHP. I talk about using the GitHub Markdown API; however, I have decided to omit this from the assignment. You can simply follow the text instructions of this assignment; the videos are optional.
In your cse322 workspace, create a folder named ajax. Place all the work you do for this assignment in this folder.
Create some data in the JSON format. Place the following in a file named ajax-data.json. Later on, we will retrieve this data and add it to a Web page using Javascript.
{
"msg": "Hello."
}
Create a file named ajax.js with the following implementation of a function named ajax. This file defines a function named ajax, which we can reuse within a Web application.
// ajax.js
//
// The following ajax function assumes that all data sent and received is in
// the form of a json encoded object sent using an http POST message.
function ajax(url, reqObj, handler) {
var req = new XMLHttpRequest();
if (!req) {
alert('Browser not supported.');
return;
}
req.onreadystatechange = function() {
var resp;
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
if (this.responseText.trim().length === 0) {
handler({});
return;
}
try {
resp = JSON.parse(this.responseText);
} catch(e) {
handler({
result: 'error',
msg: 'JSON.parse exception.\n' + this.responseText
});
}
handler(resp);
} else {
handler({ result: 'error', msg: 'Ajax error, status: ' + this.status});
}
}
};
req.open('POST', url);
req.setRequestHeader("Content-type", "application/json");
req.send(JSON.stringify(reqObj));
}
With the ajax function defined above, you can do something like the following to retrieve JSON data and insert it into the Web page. To verify this, create a file named index.html with the following contents.
<div id="container" />
<script src="ajax.js"></script>
<script>
/* global ajax */
var container = document.getElementById('container');
ajax('ajax-data.json', null, function(resp) {
container.appendChild(document.createTextNode(resp.msg));
});
</script>
Start the Apache Web server and test that the Web page displays "Hello." Change the message data to say goodbye and then reload the Web page to see the effect: the Web page should now say "Goodbye."
The next step is understand how to process data on the server side. For this purpose, we will create a PHP script.
Create msg.php with the following contents.
<?php
$request = json_decode(file_get_contents("php://input"), true);
$array = [
"msg" => "Hello, " . $request.name . "."
];
echo json_encode($array);
?>
The expression file_get_contents("php://input") simply retrieves as a string the body of the http request message sent by Javascript running inside the browser. We pass this string into the json_decode function to convert the string into a PHP associative array, which we name $request. We then create a new associative array named array with a single entry with key msg. The last line of the script converts the array into a json string with a call to json_encode and then writes this string into the output stream with the echo command. As a result, if you send { "name": "Bob" } to msg.php, it will return { "msg": "Hello, Bob." }
Create a file named msg.html that contains a text box and a submit button. When the user types their name into the textbox and then clicks the submit button, have the page send the name (as illustrated above) to msg.php. When Javascript receives a response, it should display the returned message in the Web page. You'll need to define a function that handles click events generated by the submit button. To intercept the click event, you need to add a click attribute to the submit button and set it to the click event handler function.
Send an email to the instructor with a link to your workspace. Write ajax assignment in the subject line of the email.