使用 Ajax 并将 JS 变量传递给 php 变量,$_POST 无法识别数据值


Using Ajax and passing JS variable to php variable, $_POST not recognizing data value

我正在使用AJAX将javascript变量传递给PHP。一切都运行良好,然后我改变了我的php函数执行方式的安全性。这是我的 javscript 代码:

function writetofile(file, wellname, api){
   $.ajax({
    type: 'post',
    url: 'process.php',
    data: { 
        api: api,
        wellname: wellname,
        fileName: file,
        writetoFile: true
    },
    success: function(data){
        output(api + " : " + wellname + " has been added to: " + file);
    }
});

}

.PHP:

// process.php
if ($_POST['writetoFile'])){ // i need to check here if writetofile is true, which it is
    $api = $_POST['api'];
    $wellname = $_POST['wellname'];
    $fileName = $_POST['fileName'];
    $break = "'n";
    $str = $api. " : ". $wellname . $break;
    $file = fopen($fileName,"a");
    fwrite($file, $str);
    fclose($file);
}

当我执行javascript代码时,它不会写入文件,是的,我已经检查了ajax请求是否被接受。是的,但我尝试过这样做:

.PHP

if ($_POST['writetoFile'] === true)){}

但这似乎也不起作用。谢谢你的帮助。

打开 <?php 标记后立即将错误报告添加到文件顶部

error_reporting(E_ALL); 
ini_set('display_errors', 1);

你会发现你的if语句中有一个额外的右括号 -

if ($_POST['writetoFile'] === true))
                             ------^