简体   繁体   中英

Use AJAX to get table created in PHP from MySQL without parameter

I want to write a table of images and captions to a on my page. The table is created with PHP selecting all the records from a MySQL table. The purpose of the is to display all of the available images so the user can select one to associate with the story they are posting.

Debugging the following code shows that the XMLHttpRequest object is being created, but the responseText property is empty when I debug. I went through the code 5 times looking for typos, bad syntax, etc. and cannot understand why this is not working. The code follows:

HTML

<input type="button" name="story-add-selectimage" id="story-add-selectimage" onClick="chooseImage()" value="Select an image...">
<div id="image-panel">
    <div id="hd"></div>
    <div id="bd"></div>  <!-- this is where the table from the PHP file is to be written -->
</div>

JavaScript

function chooseImage() {
    var request;
    if(window.XMLHttpRequest) {
        request = new XMLHttpRequest();
    } else {
        request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            document.getElementById("bd").innerHTML = request.responseText;
        }
        request.open("GET", "../svr/makeImageLibrary.php", true);
        request.send();
    }
}

PHP

echo '<table>';

do {
    echo '<tr>';
    echo '<td><img src="../' . $row_rsImageLibrary['path'] . '" onClick="selectImage(' . $row_rsImageLibrary['id'] . ')"></td>';
    echo '<td>' . $row_rsImageLibrary['caption'] . '</td></tr>';
} while ($row_rsImageLibrary = mysql_fetch_assoc($rsImageLibrary);

echo '</table>';

mysql_free_result($rsImageLibrary);
?>

I have tested the PHP/MySQL code and get exactly the result I expect. This result is not finding its way into the XMLHttpRequest object, though.

You have put the following code inside the request.onreadystatechange() function which never gets called.

  request.open("GET", "../svr/makeImageLibrary.php", true);
  request.send();

It should be placed outside request.onreadystatechange = function() {}

var request;
if(window.XMLHttpRequest) {
    request = new XMLHttpRequest();
} else {
    request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function() {
    if (request.readyState == 4) {

        alert(request.responseText);
    }

}

request.open("GET", "tmp.php", true);
request.send();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM