Documentation for:
• Blunt AJAX Request Handler
The Blunt Ajax Request Handler is provided "as is" without warranty of any kind, either
expressed or implied, including, but not limited to, the implied warranties of merchantability
and fitness for a particular purpose.
You expressly acknowledge and agree that use of the code is at your own risk.
- Installation
- Calling bluntAjax
- Callback Functions
- Debugging
- A Note About innerHTML
- bluntAjax Examples
- Blocking Multiple Requests
What's Not In This Document
This document does not explain how to create an XMLHttpRequest connection and is not meant to be a tutorial on the subject. By using the bluntAjax class you free yourself from needing to know how it works and simply let it work. Then you can worry about the important stuff; that is, creating the server and client side scripts to deal with the information you want to pass back and forth. Just let the Blunt Ajax Request Handler worry about the little details of actually getting that inforation where it needs to go.
Instead, this documentation and its associated Examples are meant to outline the use of the class itself.
Installation
Simply include the script file that holds the bluntAjax class in the head of your HTML document
<script type="text/javascript" src="blunt.ajax.class.js"></script>
Calling bluntAjax
To make a new ajax request, simply call the function bluntAjax() and supply any needed arguments:
Syntax:
bluntAjax(URL[, Callback_Function[, Method[, Server_Paremeters[,
HTML_Element_ID[, Pass]]]]);
Only the URL parameter is required. Also, any of the optional parameters in the function call may
be included in any order. So, if you wanted to supply server parameters but nothing else you do not
need to have empty parameters to get there like this:
bluntAjax('some_file.php', '', '', 'a=1&c=5');
Instead you simply include only what you need:
bluntAjax('some_file.php', 'a=1&c=5');
For more information on this please see the coding examples for this class.
bluntAjax Parameters
I've limited the number of parameters to what I feel is the absolute minimum and by setting some defaults and making all but one of them optional, I'm hoping that others find this as easy to use as I do.
The parametes are devided into 2 types:
- Parametes required by XMLHttpRequest
- URL
- Method
- Server_Parameters
- Callback Function Parameters
- Callback_Function
- Pass
- HTML_Element_ID
- URL
-
- URL is the only required parameter
- This parameter must be supplied in the first position, or be the first value in the parameter list
- This is the url to the page on the server that ajax will call when making the request
- This path can either be relative from the current page or absolute from the Web Root
- Callback_Function
-
Function to call when response from server is received:
- If supplied, this will be the function that is called when a response is received from the server (the Callback Function).
- If no function is provided then the default callback function is used (please see Default Callback Function below).
- For an explanation of how to create callback functions as well as a list/explanation of the parameters that will be passed to the callback function please see Callback Functions below.
- As bluntAjax is reading through the parameters passed to it, it checks to see if any of them are is a function. If it detects that the value passed is a function then it applies the value to the Callback_Function parameter.
- Method
-
- GET or POST
- Method to use when sending request to server
- bluntAjax looks at all string type values passed to it and if a match is made against either of these two values then the value is used for the Method parameter.
- The default method is POST
- Match for GET or POST is case insensitive, so GET = get = gEt = GeT
- Server_Paremeters
-
- Values that are to be sent to the server with the request
- Supplied in the form of a URL Query String with variable/value pairs, for example 'id=8&page=1'
- While examining the values passed to it bluntAjax will look at all values of the type string and if it finds the character "=" anywhere in the string then the value is assumed to be server parameters and the value will be assigned to the Server_Paremeters parameter
- None of the other parameters should legally contain the "=" character.
(Except for the possibility of the Pass parameter, see below...) - This should be a url encoded string
- HTML_Element_ID
-
- A valid HTML Element ID
- bluntAjax looks at all string type values passed to it and does a test to see if an element exists anywhere in the current page with that ID, if an element is found then then value is assigned to the HTML_Element_ID parameter.
- Pass
-
- Any value passed to bluntAjax that does not meet any of the above requirements is assigned to the Pass parameter
- Anything in this parameter will be "PASSED" unaltered to the Callback Function
- This parameter is completely ignored by the default callback function
- The pass parameter may be nearly anything, unless it will be confused with any of the other parameters
- To avoid any confusion you should use an array if you want use this parameter. The reason for this is that none of the other parameters can be and array, so any array that bluntAjax finds in the parameter list will automatically be assigned to this parameter. If you pass other types of values then you must make sure they cannot be confused for one of the other parameter types.
- For this parameter to be of any use you must supply your own callback function
Callback Functions
Callback functions are by far the hardest thing to understand about using AJAX.
All of the available frameworks use callback functions to deal with the server's response to an AJAX request. Some of the frameworks try to hide these in order to make it simpler to the average user. Some place restrictions on the type of data that may be returned, for instance requiring XML, adhering religiously to the X in AJAX (AJAX is an acronym for Asynchronous JavaScript And XML). Some even insist that you specify the mime type for both the data sent to the server as well as the data that is returned. Really, who cares, text is text no matter what the format and XMLHttpRequest really doesn't care what it's sending or recieving, so why should we as long as we build the functions on either end to deal with that data. The fewer things we have to deal with and remember the better.
What a Callback Function does is make a script more versatile. Rather than create a completely different function for making an asynchronous request in order to deal with each different response and what we want to do with each of them, instead we can have a single AJAX handler that is modified by whatever Callback Function we pass to it.
In the end, if you plan to do anything more complex than displaying the server response on your page somewhere then you will need to figure out the logistics of callback functions. Callback functions are not as complicated to figure out as some would have you believe.
The bluntAjax default callback function accomplishes the same task that other frameworks provide and does not attempt to go any further. In many cases this will be enough, but if you need to do something more complex with the server response then simply alert or display it on a page you will need to build your own JavaScript function to do the work.
A callback function is just like any other JavaScript function. You simply create the function and then supply that function when calling bluntAjax, for example:
function myCallBackFunction() {
// this function will do something with the server response
}
// call bluntAjax supplying myCallBackFunction
bluntAjax('/page.php', myCallBackFunction);
The main thing that you need to consider when building this function are the values that will be passed to it when it is called. The following parameters are passed in the same order as listed here:
MyCallbackFunction(server_response, id, pass, httpConnection, httpStatus, statusText, readError);
Callback Function Parameters
- server_response
- The data as returned by the server call. This is unaltered, so whatever your server script returns will be found in this parameter.
The server response can be almost any type of data and is decided on by the person that writes the server side script or program. While the X in AJAX stands for XML, the response does not need to be XML. You could decide to return JSON, HTML or plain text. You simply need to write a function that will deal with the type of data that you plan to return. - id
- If an HTML Element ID was passed as one of the parameters when calling bluntAjax, that ID will be in this parameter when the callback function is called. If no element id was passed to bluntAjax then this parameter will have a value of false
- pass
- If you included anything that would be considered by bluntAjax to be a "Pass" parameter, then that value will be passed to the return function, unaltered, in this parameter. If no value was given when calling bluntAjax then this parameter will have a value of false
- httpConnection
- true or false, indicates that an http connection was/was not successfully created
- httpStatus
- The last http status returned by the server. For successful operations this would be 200. For more information see: Server Status Codes
- statusText
- Any text associated with the above httpStatus number. For example, an httpStatus of 200 this would be "OK"
- readError
- If any errors occur while attempting to read the server response, the error text will be in this parameter
I've not actually encountered any errors here, so I have no information on what might actually be returned. If anyone has any links to documentation on this subject I'd be interested in hearing from you so that I may include that information here.
It is up to you to decide what should be done with any of the values sent to your callback function. For a simple example you can look at the default callback function.
Default Callback Function
It is assumed that, in many cases, the default callback function will be used. This default function expects a single type of data to be returned from the server, a text string. This text string can be just plain text or in the form of (X)HTML (both are text). If an HTML element ID is specified when calling bluntAjax (see HTML_Element_ID parameter above) then whatever is returned is put into that element. If an element is not specified then whatever is returned will simply be displayed in a JavaScript alert message.
The following is the default Callback function as it appears in the code. It is supplied with comments so that you can get an idea of the things you need to deal with if you need to write you own callback functions.
You could deal with errors differently, for instance you could place the errors into a page element or perform other actions depending on what the error was. At the point in the default function where the server response is either alerted or inserted into the page you could perform more complex operations on the response; parsing, checking, making additional AJAX requests based on the response. The possibilities are endless and beyond the scope of this documentation.
function bluntAjaxDefaultFunction(response,
div,
pass,
httpConnection,
httpStatus,
statusText,
readError) {
if (httpConnection) {
if (httpStatus == 200) {
if (readError == '') {
// call was successful
// check for existence of div
if (div !== false) {
if (element = document.getElementById(div)) {
// throw response into inner html of passed div id
element.innerHTML = response;
} else {
// passed div id does not exist
// alert error if debug is true
if (bluntAjaxDebug) {
alert('Ajax Error: Element '+div+' Does Not Exist!');
}
}
} else {
// alert response
alert(response);
}
if (pass !== false && bluntAjaxDebug) {
// pass value when calling default function
alert('passed value = '+pass);
}
} else {
// Error reading server response
if (bluntAjaxDebug) {
alert('Ajax Error reading http response: '+readError);
}
}
} else {
// Server Status is not 200
if (bluntAjaxDebug) {
alert('Ajax http Error: '+httpStatus+': '+statusText);
}
}
} else {
// failed to create connection
if (bluntAjaxDebug) {
alert('Ajax Error: Failed to create an http connection!');
}
}
}
Debugging
The final section deals with debugging. At the top of the script you will find the following:
var bluntAjaxDebug = true;
For debugging this should be set to true. To turn
debugging off set it to false.
If you look through the code example for the default callback function you will see how I have used it; errors are only displayed if debugging is turned on. You can access this value from your own callback functions in the same way during the testing process of your own scripts to get feedback on any errors that are encountered.
A Note About innerHTML
The innerHTML attribute is used to insert returned data into the element specified when using the default callback function.
innerHTML has some known issues that pertain to tables. innerHTML will break if you try to insert table elements into a table. For instance, let's say that you have a table with an id of "myTable" and the returned data is a <tr> element. Trying to insert the <tr> into the <table> will likely fail. However, inserting an entire table that starts with <table> and ends with </table> into another element usually works. Also, inserting HTML into a <td> element will work. This is just a problem with inserting <tr> into <table> or <td> into <tr>
There are debates on the use of innerHTML, but outside the known issue with tables (explained above) I feel that this is a completely valid way of inserting HTML into a page. Others will disagree. Honestly (Bluntly), I don't care. innerHTML is, in most cases, faster than DOM methods and it is also supported by most browsers (and all the browsers that I concern myself with). As long as these browsers continue to support its use, I will continue to use it. Not only does the method perform faster, it is also easier and quicker to code. I simply refuse to write manymany lines of code when I can write one line that does the same thing. There are times when DOM methods are the only logical solution, but they are not always the solution.
Blocking Multiple Requests
As a final note I would like to comment on blocking mutiple requests.
In a previous incarnation of this class I added the ability to block mutiple requests. What this meant was, by setting a specific variable to a specific value when a request was started that the ajax class would not allow additional requests until that request was complete. This was a hack and caused the code to be clunky.
The variable that needed to be set needed to be initialized in the Global scope so that the AJAX class and all the callback funtions had access to it. It also required another parameter, and there are already too many of those as far as I'm concerned, even keeping it down to the bare minimum. This is why I designed this verson to make most of them optional and allowed in any order. It was also one additional thing that needed to be worried about in the Callback Function, making these more complicated to create. It also made the code harder to read, maintain and modify.
In the end I decided that this was not the proper way to block requests. There are much more efficient/simpler ways to achieve the same effect. For instance:
- If the event that initiates the request is the clicking of a button then you could simply disable that
button before making the request and then enable it once the request is complete.
-
Another way to accomplish the above would be to have the function you are calling disabled.
This would be similar to the hack that I removed from the class, however, you would not need to deal
with specific variables and values determined by me when writing the class, they would be your variables and values which are much easier to remember.
Just to be complete I will give a simple example, note that this requires the creation of a custom Callback Function:// create a variable in the global scope // i.e. outside all functions var blockEventFuntion = false; // the event function function eventFunction(parameters here...) { // see if blockEvenFunction is false // if the blockEvenFunction = true then the // function code will not be executed if (!blockEventFunction) { // complete function actions here // block the even function blockEventFunction = true; // call bluntAjax and pass it our // custom callback function } } // the callback funtion function MyCallbackFunction(parameters here...) { // complete the callback function process // at end of callback function remove // blocking of the event function blockEventFunction = false; } -
If you need to disable all events that would call additional requests then the proper way to do this would be
with some type of browser window disabler. Not only does this effectively make additional requests imposible
but the fact that the browser has been disabled gives the user some indication that the browser is
waiting for something. The Blunt Browser Window Disabler comes in handy for this.