Amal.A
Amal.A

Reputation: 39

why javascript refuses to work more than once?

I have two separate links that call same function. They are used to load different external html doc into body of main one. They work correctly by themselves. But when one doc is loaded another one refuses to. What is a problem guys?

<li>
    <a href="#" class="decorNavi" onclick ="xmlRequest('about')" >ABOUT</a>
</li>
<li>
    <a href="#" class="decorNavi"  onclick ="xmlRequest('contactus')" >CONTACT US</a
</li>

Script:

function xmlRequest(target) {

    var targetClick;

    targetClick = target;

    if (window.XMLHttpRequest) {

        xmlRequest = new XMLHttpRequest();
    } else {
        xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlRequest.open("GET", targetClick + ".html?=" + Math.random(), true);


    xmlRequest.onreadystatechange = function () {

        if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {

            document.getElementById("midContainer").innerHTML = xmlRequest.responseText;
        }
    }

    xmlRequest.send();
}

Upvotes: 0

Views: 77

Answers (3)

Allan Stepps
Allan Stepps

Reputation: 1067

As Mike Robinson said, you are overwriting your function. Use an other name for your function. As easy as that.

function xmlRequest(targetClick) {

    var xmlRequest; // xmlRequest is no more a global. 

    if (window.XMLHttpRequest) {
        xmlRequest = new XMLHttpRequest();
    } else {
        xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlRequest.open("GET", targetClick + ".html?=" + Math.random(), true);

    xmlRequest.onreadystatechange = function () {
        if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
            document.getElementById("midContainer").innerHTML = xmlRequest.responseText;
        }
    }

    xmlRequest.send();
}

JSbin: http://jsbin.com/kehaxexo/2/

Upvotes: 2

Mostafa Shahverdy
Mostafa Shahverdy

Reputation: 2725

The name of you function "xmlRequest" and object defined in it are the same. change it to something else.

Upvotes: 1

Mike Robinson
Mike Robinson

Reputation: 25159

You're overwriting your function declaration inside your function:

function xmlRequest(target) {

and

xmlRequest = new XMLHttpRequest();

It fires once, and then replaces the function with the xmlRequest. Name the second one something else.

Upvotes: 5

Related Questions