RemoteScript Digg this entry Add this entry to del.icio.us bookmarks Add this entry to Slashdot bookmarks

As someone who is not a huge fan of large javascript libraries, it has been difficult to find a simple cross-browser wrapper for the XMLHttpRequest object.

Most of the code I've found is too ambitious, containing the remote scripting code in a larger library of functions and objects I'd probably never use. Some solutions are more restricted, wrapping only the code responsible for calling the XMLHttpRequest object.

What I need, and can't find anywhere else, is to have a remote scripting wrapper that allows for all the functionality that XMLHttpRequest does, automatically URL-encodes query strings, and returns the data to a declared function. After spending an hour or so looking for such a wrapper, I decided to write it myself.

The RemoteScript Object

Creating an instance of the RemoteScript object doesn't require any properties or methods, but instead uses function parameters. Only the first parameter (script name) is required. Listed below are all the available parameters:

Type Description Default Value
String Script name n/a
Object/String Query string null
Function Function name to pass result data GetResponse
String Method ('HEAD', 'GET', or 'POST') 'GET'
String Response type ('XML' or 'HTML') 'HTML'
Boolean Asynchronous true

Using RemoteScript

To begin scripting using the RemoteScript object, create an instance of it anywhere in your script. If you wish to make concurrent requests, create the object with the new keyword.

var objQueryString = {};
objQueryString['var1'] = 'value1';
objQueryString['var2'] = 'value2';
objQueryString['var3'] = 'value3';

RemoteScript('scriptname.php', objQueryString, ExampleResponse, 'POST');

Make sure you've defined the function that RemoteScript will call with the result data. It needs at least one parameter for the data itself. A second parameter may optionally be defined, which will contain any error information if applicable.

function ExampleResponse(sResponse, sErrorData)
{
   // Check if the response was valid
   if (sResponse === false)
   {
      alert(sErrorData); // debugging: output the error message
      return false;
   }

   // Perform your data handling here
   alert(sResponse);

   // If you want to keep polling script results, use the setTimeout function
   // The query string can be passed as a string or as an object.

   setTimeout("RemoteScript('scriptname.php', 'var1=value1&var2=value2&var3=value3', ExampleResponse, 'POST')", 5000);
   return true;
}

Changelog

Version 2.2 (released Apr. 9, 2006)

  • Increased stability and optimized code

Version 1.4 (released Oct. 3, 2006)

  • Initial public release

Download the latest version here.


1 CommentRSS

1 Pingback: www.oneajax.com wrote: [4:50am on October 17 2006]
[...]read more | digg story Share and Enjoy:These icons link to social[...]

Comments are disabled for this entry.