我正在使用Ajax将表单的值发送到我的php文件,并将其插入数据库中,具体取决于按钮将执行url的操作,
在这种情况下是insert_shirt.php,但它似乎不起作用,因为它没有发送像表单一样的数据,就好像表单完全为空
的HTML
<form method="post" id="form_shirt">
ID:
<br>
<input type="hidden" name="id_shirt" id="id_shirt" class="form-control"> Name:
<br>
<input type="text" name="name_shirt" id="name_shirt" class="form-control" required="required"> Price:
<br>
<input type="text" name="price_shirt" id="price_shirt" class="form-control" required="required">
<button id="insert_shirt" class="submit" name="btninsert">INSERT</button>
</form>
的JavaScript
$(document).ready(function() {
$('.submit').on("click", function() {
$.ajax({
url: this.id + ".php",
method: "POST",
data: $('#form_shirt').serialize(),
contentType: false,
cache: false,
processData: false,
success: function(data) {
$('#form_shirt')[0].reset();
$('#table_shirt').html(data);
}
});
});
});
的PHP
<?php
$connect = mysqli_connect("localhost", "root", "", "shirts");
$output = '';
$name_shirt = mysqli_real_escape_string($connect, $_POST["name_shirt"]);
$price_shirt = mysqli_real_escape_string($connect, $_POST["price_shirt"]);
$query = "INSERT into shirts ( name, price)
VALUES ('$name_shirt','$price_shirt') ";
if(mysqli_query($connect, $query))
{
$output .= '<label class="text-success">Data Inserted</label>';
$select_query = "SELECT id_shirt, name, price FROM shirts";
$result = mysqli_query($connect, $select_query);
$output .= '
<table id="shirts" class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>PRICE</th>
</tr>
</thead>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<tbody>
<td>' . $row["id_shirt"] . '</td>
<td>' . $row["name"] . '</td>
<td>' . $row["price"] . '</td>
</tr>
</tbody>
';
}
$output .= '</table>';
}
echo $output;
?>
最佳答案
如果您未在请求中包含contentType: "application/x-www-form-urlencoded; charset=UTF-8"
,则将其设置为默认值。您将其设置为false
,这可能就是为什么$_POST
看不到表单数据的原因。