【发布时间】:2016-07-27 17:46:09
【问题描述】:
我正在尝试使用 ajax 和预准备语句形式的查询创建一个 INSERT 语句。我之前从未使用过 AJAX 和 PDO,所以请原谅我的无知。
就这样,我得到了alert(data); 错误,但弹出的警报只是说“错误|”。这是指javascript不正确还是php文件?我相信这是 javascript,因为我什至没有让 php 文件显示在我的控制台网络选项卡中。
我的AJAX 有什么问题?
<form method="POST" id="pdo-add">
<input name="first" id="pdo-add-first" placeholder="First Name">
<input name="last" id="pdo-add-last" placeholder="Last Name">
<input name="product" id="pdo-add-product" placeholder="Product">
<input name="add" type="submit" value="Add">
</form>
AJAX
$(function() {
$("#pdo-add").on("submit", function (event) {
event.preventDefault();
var add_first = $("#pdo-add-first").val();
var add_last = $("#pdo-add-last").val();
var add_product = $("#pdo-add-product").val();
$.ajax({
url: "pdoAddSend.php",
type: "POST",
data: {
"add_first": add_first,
"add_last": add_last,
"add_product": add_product
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to insert product record!");
alert(data);
} else {
//$("#newsletter-form")[0].reset();
$('.announcement_success').html('Product Successfully Added!');
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
});
PHP
ini_set('display_errors', 1);
error_reporting(E_ALL);
$add_first = $_POST['add_first'];
$add_last = $_POST['add_last'];
$add_product = $_POST['add_product'];
try {
$host = 'localhost';
$name = '';
$user = '';
$password = '';
$dbc = new PDO("mysql:host=$host;dbname=$name", $user, $password);
}catch(PDOException $e) {
echo $e->getMessage();
}
//if(isset($_POST['add'])) {
if(isset($add_first && $add_last && $add_product) {
$stmt = $dbc->prepare("INSERT INTO users (first, last, product) VALUES (:first,:last,:product)");
$stmt->bindParam(':first', $add_first);
$stmt->bindParam(':last', $add_last);
$stmt->bindParam(':product', $add_product);
$stmt->execute();
}
【问题讨论】:
-
将 if(isset($_POST['add'])) { 更改为您的变量,例如
$add_first或$add_last或$add_product它不起作用,因为您没有$_POST['add'] -
所以这样做?
if(isset($add_first, $add_last, $add_product) { ...} -
使用
&&代替, -
不过,我认为它甚至没有进入 php 文件。网络标签中没有显示任何内容。
-
if (!empty($add_first) && !empty($add_last) && !empty($add_product)) {这样做...如果您确定所有值都应该始终具有值。如果 3 个中有空值,则不会插入
标签: javascript php jquery ajax pdo