tags:

views:

39

answers:

2

Right now I'm struggling to get this simple PHP AJAX request to work.

<html>
    <head>
      <script type="text/javascript">
        function getSuggestions(type){
          if(type == "")
          {
            document.getElementById("entries").innerHTML="test"
            return;
          }
          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("entries").innerHTML=xmlHttp.response; 
            }
          }
          xmlHttp.open("GET","getData.php?status="+type,true);
          xmlHttp.send();
        }
      </script>
    </head>
    <body>
    <div id="A" onclick='getSuggestions("A")'>Click for A</div>
    <div id="P" onclick='getSuggestions("P")'>Click for P</div>
    <div id="R" onclick='getSuggestions("R")'>Click for R</div>
    <div id="entries"></div>
    </body>
   </html>

Below is getData.php

<?php
  $status = $_GET["status"];
  echo $status;
?>

Everytime I click on any of the tags I get "undefined" in the "entries" tag. Could anybody explain why it's undefined?

+5  A: 

use xmlHttp.responseText

akellehe
+1 @akellehe - Danget...beat me to it =P
Topher Fangio
hahaha, :) thanks
akellehe
Wow can't believe I missed that :p, thank you
Albinoswordfish
+3  A: 

This is how I handle AJAX. Essentially an example of akellehe's answer

function getSuggestions(type){
    if(type == "") {
        document.getElementById("entries").innerHTML="test"
        return;
    }

    var r = getXmlObject();
    var url= "getData.php?status="+type;

    if (r.readyState == 4 || r.readyState == 0) {

        r.open("POST", url, true);

        r.onreadystatechange = function (){
            if (r.readyState == 4) {
                document.getElementById("entries").innerHTML= r.responseText; 
            }
        };

        r.send(null);

    }   
}

////////////////////////////////////
function getXmlObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if(window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        alert('Status: Cound not create XmlHttpRequest Object. Consider upgrading your browser.');
    }
}
Dutchie432
where did receiveReq come from?
Albinoswordfish
whoops. Copy-n-Paste error.. receiveReq should just be "r" - fixed in post.
Dutchie432