PHP 不将变量传递给 ajax

PHP Not passing variables through to ajax

我正在从 js 文件穿过大陆到达 PHP 文件。基本上我需要将数据插入数据库(将大陆放入)并获取它的 ID,但无论我做什么,它 returns 要么是 empty string 要么是 500 Internal Service Error.

这里是 PHP Code:

$continent = $_POST['continent'];

$sql = "INSERT INTO location_continent (`name`) VALUES ('". $continent ."')";

if(!$result = mysqli_query($con, $sql)){
    die('There was an error running the query [' . $db->error . ']');
}

$sql = "SELECT id FROM location_continent WHERE `name` = '". $continent ."'";
$result2 = $con->query($sql);
if(!$result2){
    die('There was an error running the query [' . $con->error . ']');
}
return $result2->num_rows;

这里是 JS Code:

$.ajax({
        url: 'process.php?section=continent',
        type: 'POST',
        data: 'continent='+key,
        success: function(res) {
            continentid = res;
            console.log(res);
        },
        error: function(res) {
            console.log(res);
        }
    });

通过的 Key 类似于 Africa

我在 php file 中尝试了以下方法:

return mysqli_insert_id($conn);
return $result;
$result = mysqli_query($con, $sql);

我已经挣扎了大约2个小时了。我似乎找不到错误。

备注 请注意,信息正在插入数据库中,只是我无法获取 ID。

您正在返回,但您不在函数中,因此请尝试回显 (echo mysqli_insert_id($conn);)

在 ajax 中,您需要 print/echo 输出 return 数据而不是 return 语句,因此请尝试替换

return $result2->num_rows;

echo $result2->num_rows;

您也可以发送您的查询字符串:-

$.ajax({
        url: 'process.php',
        type: 'POST',
        data: {'section':'continent','continent':key},
        success: function(res) {
            continentid = res;
            console.log(res);
        },
        error: function(res) {
            console.log(res);
        }
    });

然后通过回显检查您的 post 数据,如果更正执行查询时找不到 $con$db 在 posted 代码[=15 上定义的错误=]