Search code examples
phpajaxinternet-explorer-9

AJAX not working in Internet Explorer 9


This is my function:

<script type="text/javascript">
function loadXMLDoc() {
    var x = document.getElementById("trazi_drzava");
    var xmlhttp;
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("trazi_grad").innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", "gradovi.php?selected=" + x.value, true);
    xmlhttp.send();
}
</script>

and I call it like this:

 <select name="td" id="trazi_drzava" onchange="loadXMLDoc()">
    <option value="">Država</option>
    <?php
    $sel_grad_arr=array();
    $sel_grad_arr[]="<select name='tg' id='grad0'>  
    <option value=''>Grad</option</select>";
    if($q=mysql_query("SELECT drzava_id,drzava FROM drzava")){
    while($r=mysql_fetch_assoc($q)){
        echo '<option value="'.$r['drzava_id'].'">'.$r['drzava'].'</option>';
       }
     }else echo mysql_error().__LINE__;
    ?>
    </select><select name="tg" id="trazi_grad">
      //code that ajax should load        
    </select>

It works fine with most browsers, but with Internet Explorer 9 it doesn't work at all. Anyone have any idea why?

UPDATE: I didn't manage to do this then. So I changed logic of working totaly. Thanks everyone for answers.


Solution

  • I know this is a very old question, but still, one with no actually correct answer....

    The correct order of operations is:

    1. Create your request object
    2. open a connection
    3. Set onreadystatechange listener
    4. send request

    You have steps 2 and 3 in the wrong order, which causes problems in certain browsers.