Search

Thursday, December 21, 2006

How to make Ajax calls with Prototype

You can get prototype from http://prototype.conio.net/ Some docs and tutorials on using it: http://www.beyondstandards.com/archives/better-event-management-with-prototype/ http://www.sitepoint.com/article/painless-javascript-prototype http://www.sergiopereira.com/articles/prototype.js.html http://www.regdeveloper.co.uk/2006/12/17/ajax_prototype_tutorial/ http://particletree.com/features/quick-guide-to-prototype/ Here is an example of an Ajax call passing form variables.
/*
Function:  AjaxRequest
Arguments:
   formID    string - the form id to be used in the request
   pageUrl   string - the page url to call for the results
Return Value: None
Description:
   Retrieves the contents of the server side page defined
   in 'pageUrl' using Ajax */
function AjaxRequest(pageUrl, formID)
{
 // Disable the form - 'formID' is the id of the form that was passed in
 Form.disable(formID);

 // Serialize the form parameters to pass them along as part of the form submission
 var params = Form.serialize(formID);

 // Make an ajax request with the 'get' method, passing it the serialized form
 // and using 'ReportErrors' function to show any errors
 // and 'ProcessResults' function to process the retrieved results
 // To use the 'post' method, simply change the method to 'post'
 new Ajax.Request(
  pageUrl,
  { method: 'get', parameters: params, onFailure: ReportError,
  onComplete: function(request) {
   ProcessResults(request.responseText);
  },
  evalScript: false
  }
 );
}

/*
Function:  ProcessResults
Arguments:
   responseTextstring - the response from the Ajax call
Return Value: None
Description:
   Processes the Ajax call results */
function ProcessResults(responseText)
{
 alert(responseText);
}

/*
Function:  ReportError
Arguments:
   request    string - the response from the tracking results call
Return Value: None
Description:
   Shows an error message if an error occurs durring the ajax request */
function ReportErrors(responseText)
{
 alert(responseText);
}
// //]]>