6. XMLHttpRequest
• Modern browsers support built-in
XMLHttpRequest object
• All about sending and receiving data from
server.
• Instantiate in normal fashion:
– var xmlobj = new XMLHttpRequest();
7. Send Request to Server
var xmlobj = new XMLHttpRequest();
xmlobj.open(“GET”, // POST or GET?
“somefile.txt”, // URL
true); // async or not?
xmlobj.send(); // Send it
8. Using POST
var xmlobj = new XMLHttpRequest();
xmlobj.open(“POST”, // POST or GET?
“somescript.php”, // URL
true); // async or not?
// Specify the data you want to send via POST
xmlhttp.setRequestHeader("Content-type","application/x-www-form-
urlencoded");
// Send data
xmlobj.send(“name=Kalle”);
9. Asynchronous?
• When setting the async parameter to true, the
server side script is run in background.
• Javascript does not have to wait for the server
response.. You can
– Execute other scripts while waiting server
response
– Deal with the response when ready
• Specify a function that is called when
response is ready!
11. State of the Request
• 0: Not initialized
• 1: Server connection established
• 2: Request received
• 3: Processing request
• 4: Request Finished and Response Ready
12.
13. Status of the Request
• Also HTTP Status is received
– 200: “Ok”
– 404: “Page not found”
–…
• if(xmlobj.status == 200 &&
xmlobj.readyState == 4) { .. }
18. HTML
• Very simple way to do AJAX
• Server has fragments of HTML
• No parsing or converting
• Easy to update UI: use can use innerHTML or
standard DOM
19. XML
• Static XML Data on server or generated XML
• XML must be parsed: use DOM scripting
• Example of PHP -> XML -> AJAX
20. Example
function showResponse(req) {
// if the request is ready
if (req.readyState == 4 && req.status ==
200) {
var data = req.responseXML;
// here we have to process XML data
}
}
}
21. JSON
• JavaScript Object Notation
• Storing and exchanging text
• Smaller than XML, faster and easier to parse!
• Language Independent
23. Parsing JSON in JS
• You can convert JSON text to Object using eval
– function:
– var myObject = eval(„(„ + JSONText + „)‟);
• You should NOT use eval for security issues!
Eval executes also any js program…
• Use JSON Parses instead! It recognizes only
JSON text
24. Example (wikipedia)
var my_JSON_object = {};
var http_request = new XMLHttpRequest();
http_request.open("GET", url, true);
http_request.onreadystatechange = function () {
var done = 4, ok = 200;
if (http_request.readyState == done && http_request.status == ok) {
my_JSON_object = JSON.parse(http_request.responseText);
}
};
http_request.send(null);