我有一个php页面,我使用了一个jquery函数来根据复选框和单选按钮和文本框的值获取动态值。发生了什么事,我使用了两个警报
1。)警报(数据);
2)警报(grand_total);
在我的Jquery函数的ajax部分只是为了确保我在“grand_total”中得到什么值。一切正常,警报很好,数据正好插入表中。
然后我从函数中删除了警报,过了一段时间后我再次开始测试整个站点,我发现grand_total的值没有被插入到mysql表中。
我再次发出警报,检查出现了什么问题,一切都恢复正常。再次删除并再次启动问题。有什么想法的人出了什么问题?
这是来自 “xyz.php”
的JQUERY函数的代码片段:<script type="text/javascript">
$(document).ready(function() {
var grand_total = 0;
$("input").live("change keyup", function() {
$("#Totalcost").val(function() {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).val(), 10);
});
var textVal = parseInt($("#min").val(), 10) || 0;
grand_total = total + textVal;
return grand_total;
});
});
$("#next").live('click', function() {
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
},
success: function(data) {
// do something;
}
});
});
});
对应的HTML代码:
<form method="post" id="logoform3" action="xyz_sql.php">
<input type="text" name="Totalcost" id="Totalcost" disabled/>
<input type="submit" id="Next" name="next"/>
此代码来自 *“xyz_sql.php”* :
<?php
session_start();
include ("config.php");
$uid = $_SESSION['uid'];
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2 (total,uid)VALUES('$total','$uid');";
if($total > 0){
$res = mysql_query($sql);
}
if($res)
{
echo "<script> window.location.replace('abc.php') </script>";
}
else {
echo "<script> window.location.replace('xyz.php') </script>";
}
?>
最后但并非最不重要: echo“window.location.replace('abc.php')”; 无论数据是否插入表中都不会被执行。
答案 0 :(得分:3)
首先提交表单,如表单,而不是ajax - 因为单击“提交”按钮时没有preventDefault操作。这就是它看起来正确的原因。但是在那种形式中没有名为“grand_total”的输入。所以你的php脚本失败了。
第二 - 你将ajax绑定到id为“next”的元素 - 但是你的html中没有这样的id元素,这就是为什么永远不会调用ajax。
答案 1 :(得分:0)
РоманСавуляк的解决方案很好,但还不够。
您应该将$ total变量转换为php文件中的整数,并使用 if 和 isset()来启动代码,因此我将重写您的php代码:
<?php
session_start();
include ("config.php");
if(isset($_SESSION['uid']))
{
$uid = $_SESSION['uid'];
if(isset($_POST['grand_total']))
{
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2(total,uid) VALUES('".$total."','".$uid."')";
if((int)$total > 0)
{
if(mysql_query($sql))
{
echo "your output that will pass to ajax done() function as data";
}
else
{
echo "your output that will pass to ajax done() function as data";
}
}
}
}
并且你也可以在每个 if 语句之后传递输出,并完成js ajax函数,如:
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
}
}).done(function(data) {
console.log(data); //or everything
});