Not sure if this question will be considered "off topic". If it is, I'll remove it, but: I hadn't see this yet so I wrote it and would like to know if this is a good approach to it. Would anyone care to offer improvements to it, or point me to an example of where someone else has already written it better?
function clwAjaxCall(path,method,data,asynch)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(asynch)
{
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//alert(xmlhttp.responseText);
//var newaction=xmlhttp.responseText;
//alert('Action becomes '+newaction);
return xmlhttp.responseText;
}
}
}
if(method=='GET'){path=path+"/?"+data;}
xmlhttp.open(method,path,asynch);
if(method=='GET'){xmlhttp.send();}else{xmlhttp.send(data);}
if (!asynch){return xmlhttp.responseText;}
}
I then called it like
Just Testing
<script type="text/javascript" src="/mypath/js/clwAjaxCall.js"></script>
<script type="text/javascript">
document.write("<br>More Testing");
document.write(clwAjaxCall("http://www.mysite.com",'GET',"var=val",false));
</script>
UPDATE
I don't know if it's any better to anyone else than it was before, but I like it. :-)
I have re-written it like this:
// I wrote this with help from StackOverflow and have twaeked it some since then.
// call it like this:
//
// var holder={};
// holder.text='';
// watch(holder,function(){ //depends on watch.js. You might choose a different watch/observe method.
// //do stuff with holder.text in here
// });
// var path='http://www.example.com/?key=value';
// AjaxCall(path,"get",null,true,holder);
function AjaxCall(path,method,data,asynch,holder){
// holder is expected to be an object. It should be watched with watch.js, Object.observe or a similar method as they become available.
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(asynch){
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
holder.text=xmlhttp.responseText;
}
}
}
if(method=='GET'){path=path+"/?"+data;}
xmlhttp.open(method,path,asynch);
if(method=='GET'){xmlhttp.send();}else{xmlhttp.send(data);}
if (!asynch){return xmlhttp.responseText;}
}