2015-04-15 60 views
-1

我想创建一个表单,当提交发送信息并刷新页面,返回提交的项目的ID。我能够让PHP运行并将数据输入到服务器,但却陷入了AJAX,因为它所做的只是将文本输入到url栏中。信息不传递到PHP脚本

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; 

?>

回答

1

看来你idevent是错误的:

$('#dataSubmut').on('dataSubmit' 

这应该是:

$('#dataSubmit').on('submit' 
+0

谢谢,无法相信我错过了。你也可以看到其不更新div的任何原因? –

+0

@SamSalter哪个div?你没有在任何地方使用'data' div。 – Jai

+0

我一定会感到困惑。查看HTML代码表单底部的'Data'div。我试图让它在运行时改变php echo。 –