O'Reilly logo

Prototype and Scriptaculous: Taking the Pain out of JavaScript by Chris Angus

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

1.2. Making Ajax Calls Without Prototype

As with most things in JavaScript, using the XMLHttpRequest object (the heart of Ajax) is straightforward but verbose. If you've ever called an HTTP-based service, your code probably looks something like this:

xhr=null;

function getData(url)
{
       if (window.XMLHttpRequest)
       {
         xhr=new XMLHttpRequest()
       }
       else if (window.ActiveXObject)
       {
         xhr=new ActiveXObject("Microsoft.XMLHTTP")
       }
       if (xhr)
       {
         xhr.onreadystatechange=callback
         xhr.open("GET",url,true)
         xhr.send(null)
       }
       else
       {
         alert("XMLHTTP not supported")
       }
}

function callback()
{
       // when finished
       if (xhr.readyState==4)
       {
              //  OK
              if (xhr.status==200)
              {
              // process the result.
       }
       else
       {
              alert("error")
       }
  }
}

With Prototype, this can be written as:

function getData(url)
{
       var ar = new Ajax.Request(url,{ method: "get", onComplete : callback});
}

function callback(request)
{
       // process the result.
       var text = request.responseText;
       ...
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required