首页 > 解决方案 > 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.

标签: javascriptphpajaxpost

解决方案


您的选择框必须像这样锁定

<select id="select_1">
<option></option></select>
</select>

我认为您选择的框命名为 select_1 和 select_2,但您必须设置id而不是名称。

ps如果您使用id,请粘贴您的html代码。


推荐阅读