我正在尝试将表单中的信息插入到数据库表中,然后使用成功或失败警报消息返回到同一页面。然而,我似乎无法让它工作。这就是我现在拥有的......
HTML表格
<form id="add-menu-item">
<input type="text" name="name" class="formbox">
<input type="text" name="price" class="formbox">
<input type="submit" class="form-submit-button">
</form>
JQUERY
$("#add-menu-item").click(function()
{
addMenuItem();
});
function addMenuItem()
{
var t_name = $("#add-menu-item [name='name']").val();
var t_price = $("#add-menu-item [name='price']").val();
var errors = '';
$.ajax({
type : "GET",
url : "insert.php",
data : { name : t_name,
price : t_price, },
cache : false, timeout: 10000,
success : function() {
alert("WORKED!");
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
});
INSERT.php
<?php
include_once('_code/connectdb.php');
include_once('_code/functions.php');
$name = mysql_real_escape_string($_POST['name']);
$price = mysql_real_escape_string($_POST['price']);
$error = '';
$query = "INSERT INTO menuitems ( name, price ) VALUES ('{$name}', '{$price}')";
if (!mysql_query($query, $conn))
{
$error = mysql_error();
$return['error'] = $error;
echo json_encode($return);
mysql_close($conn);
}
else
{
$success = "Menu Item Successfully Added!";
$return['mysql'] = $success;
echo json_encode($return);
mysql_close($conn);
}
?>
由于
答案 0 :(得分:1)
不知道什么不起作用。不过我想:
$("#add-menu-item").click(function() {
addMenuItem();
});
应该是:
$("#add-menu-item").submit(function() { // you want the action to perform on submit of form and not on click??? on form
addMenuItem();
return false; // to prevent submitting the form after ajax stuff is done
});
我认为:
data : { name : t_name,
price : t_price, },
应该是:
data: ({name : t_name, price : t_price}),
答案 1 :(得分:1)
使用fireBug或类似软件轻松检测此类错误......................