【发布时间】:2021-07-30 23:46:09
【问题描述】:
所以我尝试了很多方法来解决我的网络问题。我希望在这里找到解决方案。问题是 ajax 成功函数工作,并且在网络部分它的状态代码为 200 与数据输入但它没有响应并且数据没有插入到数据库中。
html 表单:
<form action="./includes/systemcheck.inc.php" id="reg1" method="post">
<input type="text" id="reg_fname" name="fullName" class="mr_fni">
<input type="number" id="reg_uid" name="userID" class="mr_idi">
<input type="number" id="reg_pnumber" name="phoneN" class="mr_pni">
<input type="submit" name="register1" id="reg1_sub_butt" value="next"
class="cim_gSubmmit">
</form>
<p id="reg1_result"></p>
php:
if(isset($_POST['register1'])){
$fullName = $_POST['fullName'];
$userID = $_POST['userID'];
$phoneN = $_POST['phoneN'];
if(!empty($fullName) || !empty($userID) || !empty($phoneN)){
$sql = "INSERT INTO `hotelsystem` (`fullName`, `phoneNumber`, `id`)
VALUES ('$fullName', '$phoneN', '$userID')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
else{
echo "fill all fields please";
}
ajax:
window.onload = function(){
$('#reg1_sub_butt').click(function (e) {
var formData = {
'fullName' : $('#reg_fname').val(),
'userID': $('#reg_uid').val(),
'phoneN': $('#reg_pnumber').val()
}
if(formData.fullName == '' || formData.userID == '' || formData.phoneN == ''){
$('#reg1_result').html('Please fill all fields');
} else {
//if no issues attempt to push code
submitData(formData);
$('#reg1_result').show();
}
return false;
});
}
function submitData(formData){
console.log(formData);
$.ajax({
type: 'POST',
url: './includes/systemcheck.inc.php',
data: formData,
contentType: 'charset=UTF-8',
async: false,
success: function(response) {
$('#reg1_result').html(response + "work");
},
error: function() {
$('#reg1_result').html('There was an error');
}
});
}
【问题讨论】:
-
如果你只是做
submitData($('#reg1').serialize()),它将传递该表单中的所有元素。如果你在某个时候添加一些输入,那么你也不需要更新你的 JS。 -
你有一个严重的安全问题。您对SQL injection attacks敞开心扉!了解如何使用prepared statements with bound parameters,而不是将用户数据直接注入到您的查询中。永远不要相信没有明确硬编码到代码中的数据。
-
如果您将代码更改为我在第一条评论中建议的内容,它应该可以工作。
-
yes its mean that when you press the button register1 it run the code inside...不完全是。这意味着当 $_POST 数据在“register1”字段中包含一个值时,它将运行该代码。 PHP 只看到 HTTP 请求中的 POST 值,它对按钮、表单或浏览器或类似的东西一无所知。所以如果你想让它看到那个变量,你必须发送它。它不会在 AJAX 请求中自动发送。 -
其实我只是测试了一下,
.serialize()好像没有提交按钮。
标签: javascript php ajax database xmlhttprequest