简介我正在使用Ajax,PHP和SQL插入数据库。
错误::alert(data)
未定义:名字.....我以为我是在$first_name = strtoupper($_POST['first_name'])
文件中使用add.php
进行定义的。
Index.php
<script type="text/javascript">
$(document).on('click','#update_btn',function (){
$.ajax({
type:'POST',
url:'add.php',
datatype: "json",
data: {
first_name: $("#first_name").val(),
last_name: $("#last_name").val(),
position: $("#position").val(),
updated: $("#updated").val(),
},
success: function(data){
alert(data);
if (data=='ADD_OK') {
location.reload();
} else {
alert('something wrong');
}
}
})
});
<form id="form1" class="form-inline" method="post" action="">
<input type="text" name="first_name" placeholder="First Name" required>
<input type="text" name="last_name" placeholder="Last Name" required>
<select name="position" id="multiple-select-optgroup-default2" class="custom-select">
<option selected>Admin</option>
<option value="Teacher">Teacher</option required>
<option value="Staff">Staff</option>
</select>
<input type="hidden" name="updated" value='<?php echo date("Y-m-d");?>' >
<button class="btn btn-success btn-sm active" type="submit" name="save" id="update_btn"><span class="glyphicon glyphicon-plus-sign"></span> Save</button>
</form>
</script>
Add.php
<?php
$first_name = strtoupper($_POST['first_name']);
$last_name = strtoupper($_POST['last_name']);
$position = strtoupper($_POST['position']);
$updated = $_POST['updated'];
$stmt = $conn->prepare("INSERT INTO employees (first_name, last_name, position, updated) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $first_name, $last_name, $position, $updated);
$add = $stmt->execute();
if($add) {
echo "ADD_OK";
}
?>
答案 0 :(得分:2)
这是您的jQuery代码:
data: {
first_name: $("#first_name").val(),
last_name: $("#last_name").val(),
position: $("#position").val(),
updated: $("#updated").val(),
},
在这种情况下,您尝试通过提及的文本框ID来获取价值
$(“#first_name”)。val()
将代码更改为此:
data: {
first_name: $('input[name="first_name"]').val(),
last_name: $('input[name="last_name"]').val(),
position: $('input[name="position"]').val(),
updated: $('input[name="updated"]').val(),
},
希望它会对您有所帮助。