Before I embraced frameworks, I created an AJAX Object that was lightweight, easy to use and efficient. I still find it very useful when making small, standalone, single-page type web-apps and certainly proved invaluable when I wasn't.
It's usage is very simple, first include the library:
- <script type='text/javascript' src='/js/bjax.js'></script>
Then define what you want to do and away:
- <script type='text/javascript'>
- // <![CDATA[
- function responseHandler( data ){
- alert("the response was" + data.responseText);
- }
- window.onload = function(){
- Bjax.go(
- '/somefile.htm',
- null,
- { "onSuccess" : responseHandler }
- );
- }
- // ]]>
- </script>
The code is nice and efficient, killing and reusing the XMLHttpRequest Objects (or the ActiveX versions of them). So you don't need to worry about it at all.
The go function takes the follow options:
- Bjax.go(
- 'http://domain.com/path/to/file.ext', //The URL to Request
- 'key1=value1&key2=value2...', //Post data, correctly URL encoded
- { //Object literal containing options
- 'onSuccess' : function, //function to be called after successful response.
- 'onSend' : function, //function to be called on sending request
- 'onError' : function, //function to be called if a non 2xx http response code
- 'onTimeout' : function, //function to be called if request times out.
- 'timeout' : integer, //this is the number of seconds before we consider a request timed out (default 15)
- 'method' : "string" // this sets the request method, defaults to "POST"
- }
- );
If things go wrong, you can debug the AJAX requests easily using the "debug" flag. It will then alert at various stages of the process allowing you to easily see what's going on. To enable, simply set Bjax.debug to true:
- Bjax.debug = true;
There's also included a really useful function prototype, which I took the idea from from the Prototype library. The prototype is bind and always you to bind functions to objects so that when the AJAX response comes back, you can call a function in the context you where in when it left off!
If you understood that last paragraph then you know how useful that is, if you didn't, then you will find that you need this functionality at some stage or other...
Anyway, the source is available here: bjax.js (3782B) or the minified version (with debugging removed) bjax.min.js (2406B)

Comments:
Sorry, comments are closed.