php - 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';
}
解决方案
删除不必要的东西,尤其是contentType: false
从你的代码中。
那些应该被删除
cache: false, contentType: false, processData: false
当您将 contentType 设置为 false 时,将不会设置标头 Content-Type 并且 PHP 将无法读取变量并将其放入 $_POST 数组
从手册:
$_POST - 使用application/x-www-form-urlencoded或multipart/form-data时通过 HTTP POST 方法传递给当前脚本的变量关联数组
如果您想在不设置 Content-Type 的情况下阅读它,那么您需要阅读原始请求
$postRequestContent = file_get_contents('php://input');
推荐阅读
- python - Ubuntu 18.04 Python3 Selenium webdriver安装问题
- wpf - 如何将按钮保留在数据网格标题的右侧
- laravel - laravel 传递给控制器时得到未定义的变量?
- gatsby - 如何在 mdx 文件中使用 Gatsby 环境变量?
- jquery - 在元素消失/加载完成后做一些事情
- mysql - 当我打开 XAMPP 并单击 MySQL 开始按钮时,它给了我一个错误。我之前也开始了,现在不行了
- python - “x 未定义错误”而 eval(python 表达式)
- javascript - 我们不能将 obj 数据作为道具传递给 svelte 中的不同组件吗
- python - 使用 nilearn 进行 3D 图像可视化
- javascript - 如何在 Angular 9 中上传背景视频?