To be able to access external vars in JavaScript function they will have to be global vars.
When you put “var” before variable definition you specify that it is going to be a (scope) local variable – remove the “var” from
var chat_status = document.getElementById(‘chat_status’);
line, making it
chat_status = document.getElementById(‘chat_status’);
and it will work…
This has to be outside all other functions:
var chat_status = document.getElementById(‘chat_status’);
I assume that’s the case. If so, this is global but…
The problem is that you are making this assignment before the page loads. The node with the ‘chat_status’ id doesn’t actually exist yet. That’s why if you check the javascript console you will see ‘object expected’ or something like that.
There are a couple of ways to fix this.
One way is to do this:
var chat_status; //declare only
function init(){
chat_status = document.getElementById(‘chat_status’);
}
And call init() before doing whatever else you need to do.
Or, inside your function you could both declare and initialize your variable without the var keyword, like so:
function getXmlHttpRequestObject() {
chat_status = document.getElementById(‘chat_status’); //notice, no ‘var’
This will make it global also.
Or, you could do this every time:
document.getElementById (‘chat_status’). innerHTML =
Good luck.
I would suggest putting that inside of the function. So something like:
function getXmlHttpRequestObject() {
var ajax_request;
var chat_status = document.getElementById(‘chat_status’);
try{
// Opera 8.0+, Firefox, Safari
if(window.XMLHttpRequest && !window.ActiveXObject) {
ajax_request = new XMLHttpRequest();
chat_status.innerHTML = ‘XMLHttpRequest Object succesful!‘;
}
}catch (e){
alert(“Unable to make a request.”);
}
// Internet Explorer Browsers
try{
ajax_request = new ActiveXObject(“Msxml2.XMLHTTP” || “Microsoft.XMLHTTP”);
chat_status.innerHTML = ‘Msxml2 ActiveX Object succesful!‘;
}catch (e){
if(document.all) {
chat_status.innerHTML = ‘Cound not create XmlHttpRequest Object. I highly recommend updating your browser!‘;
}
}
return ajax_request;
}
window.onload = function() {
alert(getXmlHttpRequestObject());
}
I also notice that you wasn’t doing any checking to see if it was only a Safari or Firefox web browser. Since in internet explorer 8 IE will actually use the XMLHttpRequest but from what I heard it isn’t very good. The reason why it wouldn’t load was probably because of the fact that that you had your script inside of the head tag. Since it’s inside of the head tag the elements inside of the body isn’t fully loaded thus giving you a error because the object can’t be found. Give that a try and see if that works any better.
Hope this helps,
Jon W
You must be logged in to post a comment.
Comments
Leave a comment Trackback