Simple AJAX - Why won't this work ?

C

cookieplanter

I need to add content to two DIVs on page load but this just won't
work. If I call any one function, things work fine or if I trigger the
events on-click, it works perfectly. But with both together on load,
nothing happens. Please help.

Krishna.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hello, World!</title>
<script type="text/javascript">

divSwap = createR();
var globalDIV;

switchDiv('hello.htm', 'helloDiv');
switchDiv('goodbye.htm', 'goodbyeDiv');

function createR() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
function switchDiv(url, divID) {
divSwap = createR();
globalDIV = divID;
divSwap.open('GET', url, true)
divSwap.onreadystatechange = switchResponse;
divSwap.send(null);
}
function switchResponse() {
if(divSwap.readyState == 4) {
if (divSwap.status == 200) {
doMagic();
}
}
}
function doMagic() {
var myresponse = divSwap.responseText;
document.getElementById(globalDIV).innerHTML=myresponse;
}
</script>
</head>
<body>
<p><a href="javascript:switchDiv('hello.htm', 'helloDiv');">Hello</a>
&nbsp; <a href="javascript:switchDiv('goodbye.htm',
'goodbyeDiv');">Goodbye</a></p>
<h1>krishna waz ere..</h1>
<div id="helloDiv"></div>
<h1>juss checking macha</h1>
<div id="goodbyeDiv"></div>
</body>
</html>
 
R

RobG

cookieplanter said:
I need to add content to two DIVs on page load but this just won't
work. If I call any one function, things work fine or if I trigger the
events on-click, it works perfectly. But with both together on load,
nothing happens. Please help.

Krishna.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hello, World!</title>
<script type="text/javascript">

divSwap = createR();
var globalDIV;

switchDiv('hello.htm', 'helloDiv');
switchDiv('goodbye.htm', 'goodbyeDiv');

Your function calls aren't happening onload, they are occurring as soon
as the script is parsed and likely before the elements are ready. Use
something like:

window.onload = function(){
switchDiv('hello.htm', 'helloDiv');
switchDiv('goodbye.htm', 'goodbyeDiv');
}

function createR() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){

Browser sniffing as soooo passé, use something based on feature
detection:

<URL: http://jibbering.com/2002/4/httprequest.html >

or use a library that does the hard bit for you:

<URL: http://www.ajaxtoolbox.com/ >
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top