我正在尝试创建一个表单,在提交时发送信息并刷新页面,返回提交项目的ID。我能够运行php并将数据输入到服务器中,但却被AJAX困住了,因为它所做的就是将文本输入到url栏。
AJAX代码
$(document).ready(function(){
$('#dataSubmut').on('dataSubmit',function(e){
$.ajax({
url:'files/insert.php',
data:$(this).serialize(), // missing () on serialize()
type:'POST',
success:function(data){
console.log(data);
if(data != "Error") {
$("#success").html(data).show().fadeOut(5000);
}
else {
$("#error").html(data).show().fadeOut(5000);
}
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
});
});
HTML代码
<form name="dataSubmit" id="dataSubmit" action="">
Product Name: <input type="text" name="Product_Name" value=""><br>
Product Description: <input type="text" name="Product_Desc" value=""> <br>
Product Price: <input type="text" name="Product_Price" value=""><br>
Product Stock Amount: <input type="text" name="Product_Stock" value=""><br>
<input type="submit" >
<div id="data"></div>
PHP代码
<?php
$product_name = $_POST["Product_Name"];
$product_desc = $_POST["Product_Desc"];
$product_price = $_POST["Product_Price"];
$product_stock = $_POST["Product_Stock"];
$dsn = 'mysql:host=localhost;dbname=cms';
$user = 'root';
$password = '';
try {
$pdo = new PDO($dsn, $user, $password);
$pdo ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = "INSERT INTO Products (Product_Name, Product_Desc, Product_Price, Product_Stock)
VALUES (:Product_Name, :Product_Desc, :Product_Price, :Product_Stock)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':Product_Name', $_POST['Product_Name'], PDO::PARAM_STR);
$stmt->bindParam(':Product_Desc', $_POST['Product_Desc'], PDO::PARAM_STR);
$stmt->bindParam(':Product_Price', $_POST['Product_Price'], PDO::PARAM_STR);
$stmt->bindParam(':Product_Stock', $_POST['Product_Stock'], PDO::PARAM_STR);
$stmt->execute();
$newId = $pdo->lastInsertId();
echo "Data entered successfully with the id: ".$newId;
&GT;
答案 0 :(得分:1)
似乎您的id
和event
错了:
$('#dataSubmut').on('dataSubmit'
应该是:
$('#dataSubmit').on('submit'