带复选框的AJAX MYSQL PHP

时间:2015-03-24 11:24:18

标签: javascript php jquery mysql ajax

在最简单的术语中,我想实现以下目标: http://www.w3schools.com/php/php_ajax_database.asp

唯一的区别在于,它不是一个必须从下拉菜单中选择值的选项,而是一个复选框,如果项目被选中,它将作出反应,如果是,它会调整结果。

我一直在努力工作几个小时,非常感谢任何帮助。

HTML:

<html>
<head>
<script>
function showUser(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else { 
        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("txtHint").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","getuser.php?q="+str,true);
        xmlhttp.send();
    }
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
  <option value="">Select a person:</option>
  <option value="1">Peter Griffin</option>
  <option value="2">Lois Griffin</option>
  <option value="3">Joseph Swanson</option>
  <option value="4">Glenn Quagmire</option>
  </select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>

</body>
</html>

PHP文件:

<!DOCTYPE html>
<html>
<head>
<style>
table {
    width: 100%;
    border-collapse: collapse;
}

table, td, th {
    border: 1px solid black;
    padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['FirstName'] . "</td>";
    echo "<td>" . $row['LastName'] . "</td>";
    echo "<td>" . $row['Age'] . "</td>";
    echo "<td>" . $row['Hometown'] . "</td>";
    echo "<td>" . $row['Job'] . "</td>";
    echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>

更新

<form>
    <input type="checkbox" value="1" onchange="showUser(this.value)">
    <input type="checkbox" value="2" onchange="showUser(this.value)">
    <input type="checkbox" value="3" onchange="showUser(this.value)">
    <input type="checkbox" value="4" onchange="showUser(this.value)">
    <input type="checkbox" value="4" onchange="showUser(this.value)">
    <input type="checkbox" value="5" onchange="showUser(this.value)">
      </select>
    </form>

1 个答案:

答案 0 :(得分:1)

您可以使用下面给出的jquery函数serialize在调用ajax时发布所有数据。

data = $( "form" ).serialize();// data can be pass directly to ajax data parameter