开发者

XMLhttpRequest > PHP > XMLhttpRequest

I have another question. XMLhttpRequests haunt me. Everything is now in the database but I need this data to update my page on firt page load or reload. The XHR is triggered in JavaScript file which triggers PHP-Script. PHP-Script access MySQL database. But how do I get the fetched records back into my JavaScript for page update. I can not figure it out.

First my synchronous XMLhttpRequest:

function retrieveRowsDB()
{
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari

     xmlhttp=new XMLHttpRequest();

  }
  else
  {// code for IE6, IE5
     xmlhttp=new ActiveXObject("Micr开发者_开发技巧osoft.XMLHTTP");
  }

  xmlhttp.open("GET","retrieveRowData.php", false);
  xmlhttp.send(null);

  return xmlhttp.responseText;
}

Then my PHP-Script:

<?php

 $con = mysql_connect("localhost","root","*************");
 if (!$con)
 {
   die('Could not connect: ' . mysql_error());
 }

 mysql_select_db("sadb", $con);

 $data="SELECT * FROM users ORDER BY rowdata ASC";

 if (!mysql_query($data,$con))
 {
  die('Error: ' . mysql_error());
 }
 else
 {
  $dbrecords = mysql_query($data,$con); 
 }

 $rowdata = mysql_fetch_array($dbrecords);

 return $rowdata;

        mysql_close($con);

?>

What am I missing here? Anyone got a clue?


PHP scripts don't return to JavaScript. You have to echo the data (encoded in some way, for example json_encode).

Really, if you're doing any kind of ajax, you'll make your life a lot easier by using an ajax library.


There's not much technically wrong with your code so far - you just need to actually do something with it.

In your PHP file, instead of return $rowdata;, you need to output it in some way. Currently, it's just sending a blank document back to the javascript, so you'll need to echo out the code. Normally, when using a number of objects to be returned to javascript, JSON is a good format. Check out json_encode.

On the other side, in the js, you'll need to take the response and update the page in some manner. Currently, you're just returning it again.

I suggest you go through a few ajax tutorials, and consider using a framework such as jQuery to do the heavy lifting for you. You might also want to do a bit of reading on this topic, as you have some fundamental misconceptions.


The problem is xmlhttp.responseText, it doesn't exist at the time, try adding this just before your return statement:

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            doSomething(xmlhttp.responseText);
        }
    }
}

Basically you have to wait until the data is available, it takes time to make an HTTP request and get a response.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜