[SOLVED] AJAX » No repeat -- only working once

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

[SOLVED] AJAX » No repeat -- only working once

Post by Jonah Bron »

Hello, world!

I have some AJAX issues. I whiped up a quick, basic ajax connection. It works fine, unless I try it again. To get it to work again, I have to close the tab, and open the page up again in a new one.

When you click the button/link, it says "loading", until it is finished, and then the new stuff comes up. But, if you click it a second time, it says loading forever, and never opens the new stuff. The stuff is below:

Code: Select all

function getAJAX(){// get AJAX
    var ajax = false;
    try {
        ajax = new XMLHttpRequest();
    }catch (e){
        try {
            ajax = new ActiveXObject('Msxml2.XMLHTTP');
        }catch (e){
            ajax = new ActiveXObject('Microsoft.XMLHTTP');
        }
    }
    return ajax;
}
function Switch(url){// change Content
    if (getAJAX()){//if ajax returns true
        var doc = document.getElementById('CONTENT');// set var for doc content
        doc.innerHTML = 'Loading...';
        var ajx = getAJAX();
        ajx.open('GET', 'php/page.php?p='+url, true);
        ajx.send(null);
        var y = 'window.location="?p='+url+'";';
        var q = setTimeout(y, 30000);
        ajx.onreadystatechange = function (){
            clearTimeout(q);
            if (ajx.readyState==4){
                doc.innerHTML = ajx.responseText;
            }
        }
    }else{//but if not, just goto that url
        window.location = '?p='+url;
    }
}
I have experienced this problem with all of the other AJAX I've done. Why is this and how does one fix it? Has anyone else had this problem?

Thanks, world!
Last edited by Jonah Bron on Sun Jan 20, 2008 11:52 am, edited 1 time in total.
devendra-m
Forum Contributor
Posts: 111
Joined: Wed Sep 12, 2007 3:16 am

Re: AJAX » No repeat -- only working once

Post by devendra-m »

Before we send data to the server, we first write a function that will be able to receive information and store it to onreadystatechange property.

But in your code you have sent data to the server before storing function to onreadystatechange property. I think that might be creating problem.

I think it should be
1/2. ajx.open('GET', 'php/page.php?p='+url, true);
1/2. ajx.onreadystatechange=function(){}
3. ajx.send(null);
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: AJAX » No repeat -- only working once

Post by Jonah Bron »

Thanks, devendra-m.

I'll give it a whirl. :)
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: AJAX » No repeat -- only working once

Post by Jonah Bron »

You Rock!!

That was the problem. Thanks!
Post Reply