2

I'm trying my hand at creating an AJAX search and having some difficulty. Here's my JS and form:

<script type="text/javascript">// 
function prodSearch(request) {

    if (request == "") {
        document.getElementById("searchResults").innerHtml="";  
        return;
    }

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }

    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readystate==4 && xmlhttp.status==200) {
            document.getElementById("searchResults").innerHTML=xmlhttp.responseText;
        }
    }
xmlhttp.open("GET","/ps.php?country="+request,true);
xmlhttp.send();
}
</script>
<form>
<select name="countries" onchange="prodSearch(this.value)">
<option>Select a country:</option> ...
<div id="searchResults">
</div>

And here's my php:

<?php
/* Get data from form */
$country = $_GET["country"];

/* Build query */
$result = "SELECT .... ";

while( $row = $modx->db->getRow( $result ) ) {
    echo "<pre>";
    print_r($row);
    echo "</pre>";
}

?>

My query to the database works perfectly, and I can see in Firebug console that ps.php is returning results. However, I just can't seem to get it to actually populate the searchResults div with the results. What am I doing wrong?

OptimusCrime
  • 14,662
  • 13
  • 58
  • 96
Vecta
  • 2,312
  • 5
  • 28
  • 47
  • 1
    Can you `alert(xmlhttp.responseText)`? Does it alert the expected result? – Tchoupi Aug 08 '12 at 19:39
  • I placed the `alert(xmlhttp.responseText)` before the `document.getElementById...responseText` and I didn't receive an alert at all. – Vecta Aug 08 '12 at 19:49
  • 1
    Is `xmlhttp.onreadystatechange` actually called? Can you alert `xmlhttp.readystate` before this line: `if(xmlhttp.readystate==4 && xmlhttp.status==200) {` ? – Tchoupi Aug 08 '12 at 19:53
  • I did this and the alert came up with "undefined". – Vecta Aug 08 '12 at 19:57

1 Answers1

3

readyState has a capital S. Change your if condition for:

if(xmlhttp.readyState==4 && xmlhttp.status==200) {
Tchoupi
  • 14,560
  • 5
  • 37
  • 71