在div中显示PHP数据库内容

I'm setting up a website containing a page that will contain many buttons. I want to be able to click on the button to populate a div with information from a database.

I've adapted some code that I previously had, but it isn't working.

The source javascript and HTML are shown here:

<script>
function showBiog(key) {
//alert(key);

      // Get the search value
        var search_value = key

        // This time we're going to grab data from a file to display
        var filename = "functions/biography.php";

        // Send these values
        var posting = $.post(filename, { search_term: search_value });

        // Display this value in our results container
        posting.done(function (data) {
          $("#test_results").empty().append(data);
        });

}

</script>

<style type="text/css">
.test {
    background-color: #B32D2F;
    border: thin solid #DBB2B3;
    height: 50px;
    width: 250px;
}
.testresults {
    background-color: #88B32D;
    border: thin solid #DBB2B3;
    height: 50px;
    width: 250px;
}
</style>
</head>

<body>
<div class="test" onClick="showBiog(1)"><p>1</p></div>
<div class="test" onClick="showBiog(2)"><p>2</p></div>
<div class="test" onClick="showBiog(3)"><p>3</p></div>
<div class="test" onClick="showBiog(4)"><p>4</p></div>
Results
<div class="testresults" id="test_results"></div>

The HTML of biography.php is

<body>

<?php if (! $_POST["search_term"]) { ?>
  <div class="err">
      <?php echo $row_Recordset1['firstname']; ?>
  </div>

<?php } else { ?>

<?php echo $row_results['firstname']; }?>

</body>

The SQL for results in Dreamweaver is

SELECT *
FROM pilots
WHERE key LIKE colname  

with colname $_POST['search_term']

Few things...

  1. You may not need "var search_value = key" if you are not making any change or addition to it. Simply use "key" in the $.post (keep code simple).
  2. What is expected to be in "key"? Depending on what you are sending, the statement var posting = $.post(filename, { search_term: search_value }); may break due to JSON structure requirements.

To assure you are sending out the right information to the PHP, you should try something like $.post(filename, JSON.stringify({ 'search_term': key }) );

On the PHP side, you can use unserialize() to decode JSON data, then process your query.

Just a small personal note and advice: If JSON is not well formed on the POST side, PHP will get nothing, thus it will return nothing. You should always try to log or display the data received by PHP when writing AJAX calls to assure it was correctly received. Otherwise you may be chasing a bug in the wrong spot. ;)