Javascript / Ajax (no jquery!) onreadystatechange stays 1

329 views Asked by At

I'm writing a simple ajax function:

1 function setXMLHttpRequest() {
2     var xhr = null;
3     if (window.XMLHttpRequest) {
4         xhr = new XMLHttpRequest();
5     }
6     else if (window.ActiveXObject) {
7         xhr = new ActiveXObject("Microsoft.XMLHTTP");
8     }
9     return xhr;
10 }
11
12
13 var xhrObj = setXMLHttpRequest();
14 function get_commenti(id)
15 {
16     var url = "get_commenti.php?id="+id;
17     xhrObj.open("GET", url, false);
18     xhrObj.onreadystatechange = add_commenti(id);
19     xhrObj.send(null);
20 }
21 
22 function add_commenti(id)
23 {
24     if(xhrObj.readyState == 4)
25     {
26         var id_div = "commento_"+id;
27         document.getElementById(id_div).innerHTML += xhrObj.responseText;
28     }
29     alert(xhrObj.readyState);
30 }

the problem is that the readystatechange alerted on line 29 is always 1 and never 4. If i visit the page <"get_commenti.php?id="+id> with my browser it prints off the results as expected (i also tried putting an absolute path).

I have tried looking the problem up but it seems as nowadays everyone is using jQuery and I'm not yet.

It might be worth noting that I am running this on my own web server, so maybe it is because of something I have configured?

thanks!

3

There are 3 answers

1
epascarello On BEST ANSWER

You are not assigning the function

xhrObj.onreadystatechange = add_commenti(id);

You are calling it.

You need to use a closure.

xhrObj.onreadystatechange = function() { add_commenti(id); };
1
user3152069 On

I use if (xhrObj.readyState == 4 && xhrObj.status == 200) try that instead maybe ?

0
Musa On

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Properties

onreadystatechange should not be used with synchronous requests. Just use the response right after the ajax request

function get_commenti(id)
 {
     var url = "get_commenti.php?id="+id;
     xhrObj.open("GET", url, false);
     xhrObj.send(null);
     var id_div = "commento_"+id;
     document.getElementById(id_div).innerHTML += xhrObj.responseText;
 }