首页 > 解决方案 > AJAX Data Variables not being read by php file

问题描述

I am running into an issue I cannot figure out. I create a simple button that sends data with AJAX to a php file. I have the variables defined and are appearing correct in the console when clicking the button, however my PHP file is not reading the variables I am setting. The else statement in my php file is triggering.

Does anyone see why the variables are not being set in the php file?

HTML

<button class="catalogDownload downloadButton" name="Profile Catalog" id="profileCatalogPDFButton" data-catalog-now="Profile Popular Button" data-catalog-view-name="Profile Catalog">Download Now</button>

AJAX

//Download Now AJAX
var catalog_name = '';
var button_triggered = '';
$('.downloadButton').on('click', function (event) {
    catalog_name = $(this).attr('name');
    button_triggered = $(this).data('catalog-now');
    console.log(catalog_name);
    $.ajax({
        url: 'urlhere.php',
        type: 'POST',
        data: {
            'catalog_name': catalog_name,
            'button_triggered': button_triggered
        },
        success: function (data) {
            //console.log(data);
        },
        error: function(xhr, textStatus, errorThrown) {
            alert(textStatus + "|" + errorThrown);
        },
        cache: false
    });
});

PHP File

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

//$catalog_name = $_POST['catalog_name'];
if(isset($_POST['catalog_name'])){ 
    $catalog_name = $_POST['catalog_name'];
} else {
    echo 'Catalog Name is not reading';
}

标签: phpajaxpdo

解决方案


删除不必要的东西,尤其是contentType: false从你的代码中。

那些应该被删除

cache: false, contentType: false, processData: false

当您将 contentType 设置为 false 时,将不会设置标头 Content-Type 并且 PHP 将无法读取变量并将其放入 $_POST 数组

从手册:

$_POST - 使用application/x-www-form-urlencodedmultipart/form-data时通过 HTTP POST 方法传递给当前脚本的变量关联数组

如果您想在不设置 Content-Type 的情况下阅读它,那么您需要阅读原始请求

$postRequestContent = file_get_contents('php://input');

推荐阅读