Ajax with Prototype JavaScript framework

Before starting with Prototype AJAX, if you wish to have some basic Ajax talks you can visit my previous post


Prototype is a JavaScript Framework which provides an Ajax framework and other utilities. It offers a familiar class-style OO framework, extensive Ajax support, higher-order programming constructs, and easy DOM manipulation.

I love Prototype Framework due its robustness all the way 😀

Prototype’s Ajax

Besides simple requests, this module also deals in a smart way with JavaScript code returned from a server and provides helper classes for polling.

Ajax functionality is contained in the global Ajax object. Actual requests are made by creating instances of the Ajax.Request object.

Ajax.Request (All you need for using AJAX in Prototype API)

new Ajax.Request('/some_url', { method:'get' });
//Initiates and processes an AJAX request.

The first parameter is the URL of the request; the second is the options hash.
method option refers to the HTTP method to be used; default method is POST.

As Ajax requests are by default asynchronous so you must have Callbacks in order to handle server response data and those callback methods should be passed in the options hash.

Ajax response callbacks

new Ajax.Request('/some_url',
 onSuccess: function(transport){
 var response = transport.responseText || "no response text";
 alert("Success! \n\n" + response);
 onFailure: function(){ alert('Something went wrong...') }

Here, two callbacks are passed in the hash that alert of either success or failure; onSuccess and onFailure are called accordingly based on the status of the response.
Other available callbacks are:

  • onUninitialized,
  • onLoading,
  • onLoaded,
  • onInteractive,
  • onComplete and
  • onException.

They all match a certain state of the xmlHttpRequest transport, except for onException which fires when there was an exception while dispatching other callbacks.

Parameters with the request

You can pass the parameters for the request as the parameters property in options:

new Ajax.Request('/some_url', {
  method: 'get',
  parameters: {name: 'Tonu', age: 27}

The main idea to use parameter option is sending the contents of FORM with the request and yes of-course Prototype has it’s helper to do serialize.

new Ajax.Request('/some_url', {
  parameters: $('id_of_form_element').serialize(true)

Global responders

Again if you wish to register some callbacks which will fire on certain state and will work with every Ajax.Request
then you have
Ajax.Responders, a repository of global listeners notified about every step of Prototype-based AJAX requests.

If you wish extend your reading then Click Here

More on Ajax with Prototype Here

Cheers! 😀