javascript - Ajax does not pass POST
问题描述
I have a form and I need to POST data to a compute.php file. I have to pass the content of two select fields, named select_1 and select_2. My fiire button has a onclick='go()' call.
My script code is as follows:
function go() {
var sel_1 = document.getElementById('select_1').value;
var sel_2 = document.getElementById('select_2').value;
$.ajax({
type: "POST",
url: "compute.php",
data: "select_1=" + sel_1 + "&select_2=" + sel_2,
dataType: "text",
success: function(data,status)
/* ------------ for debug I have an alert with a response ---- */
{
alert("passed data are: " + data + "\nStatus: " + status);
},
error: function(data,status)
{
alert("passed data are: " + data + "\nStatus: " + status);
}
});
}
On the php side my compute.php file has code as follows:
$selection_1 = $_POST["select_1"];
$selection_2 = $_POST["select_2"];
$sqladd = "INSERT INTO table SET column_1 = '$selection_1', column_2 = '$selection_2';";
if (mysqli_query($conn, $sqladd)) {
$resultadd= mysqli_query($conn, $sqladd);
// ------- then for debug purpose
echo "inserted row with col_1 --->" . $selection_1 . "<--- and col_2 --->" . $selection_2;
} else {
// ------- either, still for debug purpose
echo "not inserted. ";
echo "Error: " . mysqli_error($conn);
}
Now the alert box shows that js has correctly got the values of the two select fields, and I also get back a success status, but my debug echo from compute.php shows empty values for selection_1 and selection_2, and the table row is inserted but in the inserted row the table columns are empty. Apache log shows two notices: PHP Notice: Undefined index: select_1 in compute.php and PHP Notice: Undefined index: select_2 in compute.php. So PHP doesn't receives the two POST values. What am I doing wrong? I have the following rules and conditions in .htaccess:
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R,L,NC]
RewriteCond %{REQUEST_FILENAME}.php [NC]
RewriteRule ^ %{REQUEST_URI}.php [L]
Can they block POST? If yes, how can I get the same result without blocking POST? I need externally redirect /dir/foo.php to /dir/foo and to internally redirect /dir/foo to /dir/foo.php.
解决方案
您的选择框必须像这样锁定
<select id="select_1">
<option></option></select>
</select>
我认为您选择的框命名为 select_1 和 select_2,但您必须设置id而不是名称。
ps如果您使用id,请粘贴您的html代码。
推荐阅读
- sql - SQL 来构造图形小部件的数据
- java - 在 Java 中的 JPanel 上绘制随机不重叠的矩形
- javascript - 如何在 1 次单击时使用 document.getElementById 调用 2 个 ID
- java - 如何异步设置一个值并在稍后阶段获取它
- javascript - 嵌套的 JSON 调用:未捕获的 SyntaxError:模板表达式中缺少 }
- java - Java中带有Eclipse的JOptionPane不起作用
- windows-10 - 这个程序中的这个杂散错误是什么?
- batch-file - 我可以将发送给我的 LAN 消息放入程序中进行解密吗?
- python - Python中选定列的条件计数
- python - 在 Django 框架中覆盖 __eq__ 和 __hash__ 的潜在副作用是什么?