这是我的html代码。我想使用ajax将选项值插入数据库。请帮助
if($row['showComment']=='S'){
echo "<td><select class='col-md-6 form-control form-control-lg combSelect' id='scmnt' name='setcombo1'><option>Select</option><option value='S' selected>Show</option><option value='H'>Hide</option><option value='P'>Pending</option></select></td>";}
elseif ($row['showComment']=='H') {
echo "<td><select class='col-md-6 form-control form-control-lg combSelect' name='setcombo1'><option>Select</option><option value='S' >Show</option><option value='H' selected>Hide</option><option value='P'>Pending</option></select></td>";}
elseif ($row['showComment']=='P') {
echo "<td><select class='col-md-6 form-control form-control-lg combSelect' name='setcombo1'><option>Select</option><option value='S' >Show</option><option value='H'>Hide</option><option value='P' selected>Pending</option></select></td>";}
else{
echo "<td><select class='col-md-6 form-control form-control-lg combSelect' name='setcombo1'><option selected>Select</option><option value='S' >Show</option><option value='H'>Hide</option><option value='P'>Pending</option></select></td>";}
这是我的ajax脚本
$('.combSelect').on('change', function(){
var donor_id = this.value;
$.ajax({
type: "POST",
data:'donor_id='+donor_id,
url: "addComment.php"
});
});
答案 0 :(得分:0)
使用此代码
<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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.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>
然后创建一个ajax文件
<?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="INSERT INTO MyGuests (firstname)
VALUES ('$q')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}