I'm trying to create a form that when submitted sends the information over and refreshers the page, returning the id of the item submitted. I am able to get php to run and enter the data into the server but getting stuck with the AJAX, as all its doing is entering the text into the url bar.
AJAX Code
$(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 Code
<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 Code
<?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;
?>