Beginners Guide to AJAX

Follow Roger Facebooktwittergoogle_pluslinkedinrss

What is AJAX?

AJAX is magic. It lets developers retrieve information from the server at runtime without a page reload. This means that a page can change in the background while a user is interacting with the page. The most well-known example is Google Suggest – when you start typing a search query in the Google search field, a drop-down with suggested searches appears. This drop-down is generated using AJAX.

AJAX is an acronym for “Asynchronous JavaScript and XML”. So, what is “Asynchronous”? Asynchronous means one input/output (I/O) process can continue before another’s transmission is completed. In other words, on the browser side the page remains rendered while in the background the application makes a request from the server. Conversely, “Synchronous” means you wait for the page to render while the request is being completed. That’s enough on the semantics. Read the remainder of this post, then come back and reread this description.

Ancient Browser Compatibility

Be patient. The code is coming. First, a short history lesson – you need this to understand the bits we have to add for cross-browser compatibility.  AJAX originated as a Microsoft Internet Explorer ActiveX object called XMLHTTP. Other browsers later added the XMLHttpRequest class. Internet Explorer 7 added XMLHttpRequest. So, in order for your code to remain compatible with browsers older than  IE7, you need to offer the ActiveX object.

 
 var httpRequest;
 if (window.XMLHttpRequest) { // Modern Browsers
 httpRequest = new XMLHttpRequest();
 }
 else if (window.ActiveXObject) { // IE 6 and older
 httpRequest = new ActiveXObject("Microsoft.XMLHTTP");

 }

The code above is just to demonstrate the cross-browser bits. We need to add some lines for production code.

 HTTP Verbs

If you have built a form that reads or writes to the server, you are likely familiar with GET and POST – the values that can be set for the method attribute in forms. These methods are also known as verbs. If you are not familiar with creating HTML forms, read on; I think things will become more clear. The HTTP standard allows for 9 verbs: GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE and CONNECT. For the purposes of this post I am not going into the details on verbs. We’ll stick with GET (basically “Read”) and POST (“Write”). In fact, in our example, we’ll use GET. GET is what your browser uses when you request a web page.

Sending a Request to the Server

Two lines are required in order to make a request of the server. The first uses the open() method of the JavaScript XMLHttpRequest object. The second uses its send() method.

httpRequest.open('GET', 'http://www.example.org/some.file', true);
httpRequest.send(null);

When I first started with JavaScript I had trouble getting my head around concepts like this request. So, hopefully I can help you avoid the same struggle. XMLHttpRequest is a built-in JavaScript class. In my example, we instantiated an object, httpRequest, on that class. The methods open() and send() are functions (functions within an object are called methods) within that class. To better understand JavaScript Objects, read my post about them – JavaScript Objects.

open()

The open() method accepts the parameters as follows:

open(
DOMString method,
DOMString url,
optional boolean async,
optional DOMString user,
optional DOMString password
)

I included the first three parameters.

The first parameter is the method or verb (see the previous section). Be sure to use the HTTP standard of all uppercase for the method; some browsers’ JavaScript engines throw an error otherwise. The second is the URL of the resource we are accessing. The third is a Boolean (true or false) indicating whether or not to make the request Asynchronous; yes, the “A” in AJAX stands for Asynchronous, and you can override it. Setting the value to “false” means that  the send() method won’t return until after the response is complete – making the connection/request Synchronous.

send()

The send() method is used to send data to the server. For the POST method this would include any data the server side needs in order to complete the request. i.e. form data. The format of this data must be what the server is expecting. Documents, JSON, SOAP, or query string are typical. Since we are using GET, I set the send data to NULL (basically a controlled way of sending empty).

Handling the Response

We need to receive the response from the server, check its status, then, if all is OK programmatically handle the response. The event on the XMLHttpRequest Object that handles the response is onreadystatechange. We set this event to a function that specifies what will happen once the server response is complete.

function handleResponse() {
    if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
            alert(httpRequest.responseText);
} else {
            alert('There is a problem with the request or response.');
}
    }
}

The readystate passes through 5 stages (counted on a zero base): 0 – Waiting or uninitialized, 1 – loading, 2 – loaded, 3 – interactive (user may interact with the response), 4 – complete. Our function above waits until the readystate is complete, at stage 4. When readystate is at complete, we check the status. A status of 200 is “OK”, which is what we want on GET request. The other possibility is 404 – “Not Found”. In the function above I simply send the response to an alert box, to indicate success.

All Together Now (the complete code)

var httpRequest;
document.getElementById("ajaxLink").onclick = function() { makeRequest('http://www.example.com/test.html'); };
function makeRequest(url) {
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
try {
            httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
        catch (e) {
            try {
                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
            catch (error) {}
        }
    }

    if (!httpRequest) {
        alert('Giving up :(  Cannot create an XMLHTTP instance');
return false;
}

httpRequest.onreadystatechange = handleResponse;
httpRequest.open('GET', url);
httpRequest.send();
}

function handleResponse() {
    if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
            alert(httpRequest.responseText);
} else {
            alert('There was a problem with the request.');
}
    }
}

Conclusion

I hope that this post is helpful. I spent much time trying to figure out the technologies described here. My intent was to put all the things I found in various places in one concise post. Keep in mind that I attempted to simplify things. I will write a more advanced post in the future.

Please post ideas, suggestions, questions, or ways that I can improve this post, in the comments. I will watch them.

Thanks for reading!

Share with your social networks Facebooktwittergoogle_plusredditpinterestlinkedinmail

JavaScript Objects

Follow Roger Facebooktwittergoogle_pluslinkedinrss

Introduction

In JavaScript an object is a collection of properties. Properties consist of a variable name and its value. A property’s value can be a number, a string, another object, a boolean, an array, or a function. Properties set to equal a function are known as methods. Within JavaScript there are 3 types of objects – objects that are part of the language construct, objects that are part of the browser (like DOM elements), and objects created by your program at runtime.To help make the intangible world of a computer program make sense, think of JavaScript objects like objects in the real world. In the real world objects have a collection of properties. Let’s use a person as an example object. A person has an eye color, hair color, height, weight, etc. These are properties of our person. A person also can walk, talk, run, eat, sleep, etc. These properties are methods – things our person can do.

Creating an Object

There are several ways to instantiate (create) an object in JavaScript. So, if you are learning, and have read elsewhere about creating objects, don’t let my choice of creation method in my examples confuse you. If you are coming to JavaScript from another OOP(Object Oriented Programming) language, you may have used classes to set up the structure of your objects. PHP, C#, C++, and Java are all class-based languages. JavaScript does not use classes; it is a prototype-based language. However, a class keyword is coming in the Ecmascript 6 (the parent of JavaScript Wikipedia Entry) definition. Class-based and prototype-based determine the programming architecture of inheritance, or sharing of object properties with other objects. But, don’t get hung up on class-based versus prototype-based. I’ll explain prototype inheritance in more detail in a future post.

Now, some Code

Let’s create our person as a JavaScript Object. Behind the scenes, a JavaScript Object is a function. So, we are going to begin there. This function is known as the constructor.

var Human = function(){};

Next, we’ll create an instance of the object.

var person = new Human();

Then, we can add some properties to our object. The flexibility of JavaScript means there are multiple ways of adding properties. I am going to use dot notation here. So, this way of representing properties is object.property.

person.eyes = “blue”;
person.hair = “blonde”;
person.height = “5.5″
person.weight = “110″;

 Now, we need to have our object (person) do something. We’ll add a method. A method is a property that is a function. Let’s have our person introduce herself.

person.introduce = function(){
alert("Hi! I have " + person.eyes + " eyes and " + person.hair + " hair");
};

Notice that to attach the method to our object all we do is create a property of the object, and assign the function as the value of that property. Pretty cool!
Here is the complete code:

var Human = function(){};

var person = new Human();
person.eyes = “blue”;
person.hair = “blonde”;
person.height = “5.5″;
person.weight = “110″;

person.introduce = function(){
alert(“Hi! I have “ + person.eyes + ” eyes and “ + person.hair + ” hair”);
};

person.introduce();

Get a JSfiddle with a working version of the complete code here. Play around with the code in JSfiddle – you’ll learn lots that way.

Hopefully, this introduction gives you a basic understanding of JavaScript objects. In future posts I plan to expand on this beginning. So, stay tuned!

PLEASE post any questions, comments, or suggestions in the comments. I’d love to hear from you!

 

Share with your social networks Facebooktwittergoogle_plusredditpinterestlinkedinmail