You are on page 1of 4

AJAX Basics

xhr = new XMLHttpRequest();


xhr.onreadystatechange = xhrHandler();
xhr.open("POST", url);
xhr.send(postData);
State 4 means “done”
...
function xhrHandler() {
if (this.readyState != 4) {
return;
}
if (this.status != 200) {
// Handle error ...
return;
}
...
var text = this.responseText; Response available as
var document = this.responseXML; raw text or XML
}
CS 142 Lecture Notes: Forms Slide 1
Higher-Level AJAX Example

Watch this element


<%= observe_field(
for change
"userName",
:frequency => 0.25,
:update => "completionMenu",
:url => {:action => "nameChoices"}
) %>

Issue AJAX request here

Replace this element’s


innerHTML with response

CS 142 Lecture Notes: Forms Slide 2


JSON Example

{name: "Alice", gpa: 3.5,


friends: ["Bill", "Carol", "David"]}

CS 142 Lecture Notes: Forms Slide 3


CS 142 Lecture Notes: Forms Slide 4

You might also like