我正在使用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;
?>
答案 0 :(得分:2)
如果您未在请求中包含contentType: "application/x-www-form-urlencoded; charset=UTF-8"
,则设置为默认值。您将其设置为false
,这可能是您$_POST
无法看到您的表单数据的原因。
答案 1 :(得分:0)
尝试使用像这样的ajax .post方法 并确保在表单标记
中包含action =“{your php file}”$(document).ready(function() {
$('.submit').on("click", function() {
var id = $('#id_shirt').val();
var name = $('#name_shirt').val();
var price = $('#price_shirt').val();
$.post("{your php file}",
{
id_shirt: id,
name_shirt: name,
price_shirt: price,
},
function(data,status){
$('#form_shirt')[0].reset();
$('#table_shirt').html(data);
});
});
});
});
这是ajax .post和.get的w3手册的链接 https://www.w3schools.com/jquery/jquery_ajax_get_post.asp