Addeventlistener with ajax not working well

I want to show the content of a txt file inside a 'div', so I'm calling my function with a button, but the functions triggers even if I don't push the button, here's my HTML code:

<body>
<form>
     <input id="showF" type="button" value= "Show File" />
</form>

 <div id="contaniner" style="background-color:#99FF66;">
 <p>It will show the txt content</p>
 </div>

</body>

And my js code:

 window.onload=function(){
    document.getElementById("showF").addEventListener("click",sacardatos('P1.txt','container'),false);
 }

 function sacardatos(data, idDiv){
     var XMLHttpRequestObject = false;
 if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
 } else if (window.ActiveXObject) {
    XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
 }

    if(XMLHttpRequestObject) {
        var objeto = document.getElementById(idDiv);
        XMLHttpRequestObject.open("GET", data);
        XMLHttpRequestObject.onreadystatechange = function(){
            if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
                objeto.innerHTML = XMLHttpRequestObject.responseText;
        }
    }
    XMLHttpRequestObject.send(null);
 }
}

Answers:

Answer

You are calling a function instead of passing in as a anonymous method.

window.onload=function(){
    document.getElementById("showF").addEventListener("click" , function(){
        sacardatos('P1.txt','container');
    },false);
}
Answer

The second argument to addEventListener should be a function. You're not passing a function, you're calling the function immediately and passing the result. Change to:

document.getElementById("showF").addEventListener("click", function() {
    sacardatos('P1.txt','container');
}, false);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.