I tried to insert data into database by using ajax and php. However, I have no idea why it is not working. I have tested the html file, all the itemName, category, price are valid and the php file return me "success" just the data inserted to database is empty.
$(document).ready(function(){
var url = "http://domain/addProduct.php?callback=?";
$("#addProduct").click(function() {
var itemName = $("#itemName").val();
var category = $("#select_category").val();
var price = $("#price").val();
var dataString = "$itemName=" + itemName + "&category=" + category + "&price=" + price + "&addProduct=";
if ($.trim(itemName).length > 0 & $.trim(category).length > 0 & $.trim(price).length > 0) {
$.ajax({
type: "POST",
url: url,
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {
$("#addProduct").val('Connecting...');
},
success: function(data) {
console.log(data);
if (data == "success") {
alert("Successfully add item");
} else if(data="failed") {
alert("Something Went wrong");
}
}
});
}
return false;
});
});
<?php
header("Access-Control-Allow-Origin: *");
require("config.inc.php");
$name = mysql_real_escape_string(htmlspecialchars(trim($_POST['itemName'])));
$category = mysql_real_escape_string(htmlspecialchars(trim($_POST['category'])));
$price = mysql_real_escape_string(htmlspecialchars(trim($_POST['price'])));
$date = date("d-m-y h:i:s");
$statement = $pdo->prepare("INSERT INTO product(name, category, price, date) VALUES(:name, :category, :price, :date)");
$statement->execute(array(
"name" => $name,
"category" => $category,
"price" => $price,
"date"=>$date
));
if($statement)
{
echo "success";
}
else
{
echo "failed";
}
?>
You can't use date
as your table column. date
is a predefined/reserved keyword. Change the name of your date column into your database and modify your sql query
and try again.
replace this code:
dataString="$itemName="+itemName+"&category="+category+"&price="+price+"&addProduct=";
to:
dataString="itemName="+itemName+"&category="+category+"&price="+price+"&addProduct=";
and replace this code too:
if($.trim(itemName).length>0 & $.trim(category).length>0 & $.trim(price).length>0)
to:
if($.trim(itemName).length>0 && $.trim(category).length>0 && $.trim(price).length>0)
Because & is a Bitwise Operator But && is Logical Operator, So in this condition we always use logical operator.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.