Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Jul 2007
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    XMLHTTPREQUESt won't work!

    Hello,
    Code:
    function getUsersXYZ() {
    xmlhttp=null;
    if (window.XMLHttpRequest)
      {// code for IE7, Firefox, Opera, etc.
      xmlhttp=new XMLHttpRequest();
      }
    else if (window.ActiveXObject)
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    if (xmlhttp!=null)
      {
     xmlhttp.open("GET", "getproomu.php",true);
     xmlhttp.onreadystatechange=function() {  
      if (xmlhttp.readyState==4) {  
    alert(xmlhttp.responseText); 
    getElementById("screen").innerHTML = xmlhttp.responseText;  
    
    }  
    }
    }		
    }
    As may be obvious from the above coding, I'm trying to use xmlhttprequest to get a php file which contains parts of my website. It dosen't work though, it dosen't alert the resultant text. Does anyone know what the problem is?
    By the way, the php file contains the following code:
    Code:
    <?php
    include("config.php");
    $sql = mysql_query("select * from users where in_room = '$logged[in_room]'") or die(mysql_error());
    while($usr=mysql_fetch_array($sql)) {
    $x = $usr[x];
    $y = $usr[y];
    $z = $usr[z] * 10000;
    echo "<img src='$usr[view]' style='position: absolute; left: $x; top: $y; z-index: $z;'>";
    }
    
    ?>
    Last edited by Miles; 06-14-2008 at 02:10 PM.

  • #2
    bdl
    bdl is offline
    Regular Coder
    Join Date
    Apr 2007
    Location
    Camarillo, CA US
    Posts
    590
    Thanks
    4
    Thanked 83 Times in 82 Posts
    The first glaring issue I see, you're missing a call to send, e.g.
    Code:
    xmlhttp.send(null);
    Try changing your code slightly, e.g.
    Code:
    function getUsersXYZ() {
      xmlhttp=null;
      if (window.XMLHttpRequest)
      {// code for IE7, Firefox, Opera, etc.
        xmlhttp=new XMLHttpRequest();
      } else if (window.ActiveXObject)
      {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    
      if (xmlhttp!=null)
      {
    
        alert("Valid XMLHttpRequest object found");
    
        // call to initialize the request
        xmlhttp.open("GET", "getproomu.php",true);
    
        // onreadystatechange callback
        xmlhttp.onreadystatechange=function() {
    
          alert("Inside the request callback function");
    
          alert("readyState at this time: " +xmlhttp.readyState);
    
          if (xmlhttp.readyState==4) {
    
            alert("HTTP status: " +xmlhttp.status +" : "+ xmlhttp.statusText);
    
            alert("The response:\n" + xmlhttp.responseText);
         
            //getElementById("screen").innerHTML = xmlhttp.responseText;  
          }  
        }
    
        // call to send the request
        xmlhttp.send(null);
      }		
    }
    Notice the extra alert()'s built in, and I've commented out the DOM code. It's a Good Idea to take it step by step and use alert() in your code to troubleshoot prior to actually 'doing something' with it.


    Now, having looked over your JS code, let's look at the PHP.

    Some things to consider when troubleshooting:
    • Does the PHP script output anything as a standalone script? This is the first thing you should be looking at.
    • Does the 'config.php' make a successful connection to the MySQL server and select the database?
    • Where is the variable (array index) $logged[in_room] come from? If this isn't initialized in the script, it's an empty string to MySQL, so your SELECT statement may carry on just fine, it just doesn't return a result set.
    • Any PHP script that returns data to an Ajax (XMLHttpRequest) call should never use die(). It should either handle errors gracefully or act as if the error never took place. The Ajax call should carry on and the JS / DOM code should use cached data in case the SELECT statement fails.
    • You have columns named 'x', 'y' and 'z'? What does that have to do with a user? It would appear as though your database isn't properly normalized, if you're storing images in the `users` table. Not necessarily anything to do with the problem, just an observation.
    • You're using echo inside the while() loop; is this your intent? Your script will use echo once, returning the data to the Ajax call, then what? Do you even need a while() loop? How many records do you expect to match on that conditional? Your while() loop, if it's actually necessary, should build a string to be sent via echo after the loop.


    Whenever I code a PHP script to be used in this way, I always make sure I have a default return value, and never attempt to return something inside a loop, e.g.
    (pseudocode)
    PHP Code:
    <?php
    // if no value was passed, or it doesn't mean a condition, exit
    if ( !value_passed || conditional(value_passed) ) exit();

    // default return value
    $output='';

    // run the SELECT statement
    $sql"SELECT somecolumn FROM sometable WHERE id={value_passed}";
    $result= @mysql_query($sql);

    // handle the result
    if ( $result && mysql_num_rows($result) > ) {
      while( 
    $rowmysql_fetch_assoc($result) ) {
        
    // build a string from the results
        
    $output.= $row['somecolumn'] ."\n";
      }
    }

    // return and exit
    header("Content-type: text/plain");
    echo 
    $output;
    exit();
    ?>
    Things to notice:
    • If the script doesn't receive the input it expects, exit. You can also use some logic here to ensure the Ajax code is the only thing that is allowed to access this script. I personally send a header with the XMLHttpRequest object to be checked in the receiving PHP script.
    • There is a default value should the SQL statement fail or the result set is empty.
    • The logic dictates whether or not the $output variable contains data or not to be returned
    • I use the concatenation operator ('.') to create an output string, then send the entire string after the while() loop is complete. When returning, it might return some value from the database, or the default value (an empty string). This ensures your JS code never gets 'stuck' because of bad PHP or an empty result.
    • The use of header() to provide a Content-Type HTTP header to the Ajax call. This is especially useful when returning something other than plain text of course, like JSON or XML.


    Refer to the Wikipedia article on XMLHttpRequest for more details.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •