Friday, January 23, 2009

A simple basic and easy AJAX call for Javascript

Anyone looking to extend the use of their website or webpage will find that using AJAX calls will add a added dimension to the site. The use of AJAX allows you to call any external page and get the requested information and post it to your page without refreshing. It is rather simple. The following code can be transformed to do what you need but it gives the basic structure.

What you need is an event to fire.


<span onclick="AJAXCall('http://kcwaldo.blogspot.com/2008/10/simple-sql-select-statement.html','&Action=test','myspan')"> Click me</span>

<div id='myspan'>
Return information goes here.
</div>

Below is the script needed to run the event.


<script>

var hURL = '';
var hParamValues = '';
var hAc = '';
var hParamValuesa = '';

function handleHttpResponse()
{
if (http.readyState == 4)
{
if (http.responseText.indexOf('invalid') == -1)
{
document.getElementById(ActiveContainer).innerHTML = http.responseText;
isWorking = false;
//This is the queue.
if (hURL != '' && hParamValues != hParamValuesa){
AJAXCall(hURL,hParamValues,hAc);
hParamValuesa = hParamValues;
}
}
}
}
//url = url you are to get the data from
//paramvalues = are posted to the url. If you need querystring values then include //them in the URL.
//ac = the active container that the data returned will be pasted into. probably a //div or td or span

function AJAXCall(url,paramvalues,ac)
{

try
{
if (!isWorking && http)
{
if (ac == ''){return false;}
ActiveContainer = ac
document.getElementById(ActiveContainer).innerHTML = '';
http.open("Post", url, true);
http.onreadystatechange = handleHttpResponse;
isWorking = true;
http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
http.send(paramvalues);
}
else{
hParamValues = paramvalues;
hURL = url;
hAc = ac;
return false;
}
return true;
}
catch (e)
{
return false;
}
}

//This function creates a HTTP Object. It works in any browser, so far at least.
function getHTTPObject()
{
var xmlHttp;
try
{ // Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{ // Internet Explorer
//alert(e.description);
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
//alert(e.description);
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
//alert(e.description);
//alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}

var ActiveContainer = '';
var isWorking = false;
var http = getHTTPObject();

</script>

Something the function above will do is to Queue up a second call so that. This is so if you have a list of links that you are showing a picture for it will make the first and last call but very few in between. Without the queue you can get very clunky behavior.

Please leave me a comment if you find this useful or something wrong.

No comments:

Post a Comment