[英]In Wordpress: post jQuery variable using AJAX for later use in PHP
In WordPress, I'm trying to post a jQuery variable using AJAX to use later in PHP. 在WordPress中,我尝试使用AJAX发布jQuery变量,以便稍后在PHP中使用。 I've setup my jQuery function and the function to echo the variable. 我已经设置了我的jQuery函数和该函数以回显该变量。
I am getting the success message from the jQuery function in the console log, but the $_POST variable is null. 我从控制台日志中的jQuery函数获取成功消息,但是$ _POST变量为null。
Below are the functions I've setup: 以下是我设置的功能:
function foo_carousel_js() { ?>
<script>
jQuery(document).ready(function($) {
var ajax_url = "<?php echo admin_url('admin-ajax.php'); ?>";
var count_ci = $('.selector li').length;
$.ajax({
type: 'POST',
url: ajax_url,
data: {
action : 'foo_item_count',
count_ci : count_ci
},
success:function( data ) {
console.log( data );
}
});
});
</script>
<?php }
add_action( 'wp_footer', 'foo_carousel_js' );
function foo_item_count() {
$k = esc_html( $_POST['count_ci'] );
echo $k;
wp_die();
}
add_action('wp_ajax_foo_item_count', 'foo_item_count');
add_action('wp_ajax_nopriv_foo_item_count', 'foo_item_count');
I had the exact same question/problem a few years ago. 几年前,我有完全相同的问题。 Turns out you cannot access that Ajax sent value anywhere else within WP besides your functions.php and of course plugin files. 事实证明,除了functions.php和插件文件之外,您无法访问该Ajax在WP中其他任何地方发送的值。 Reason being that while doing Ajax, WP only reloads the mentioned files (functions and plugins) but not the rest of the template structure. 原因是在执行 Ajax时,WP仅重新加载提到的文件(功能和插件),而不重新加载模板结构的其余部分。 Therefore, while $_POST
has your data, you can't render it on a template file because those are already loaded. 因此,尽管$_POST
拥有您的数据,但是您无法将其呈现在模板文件上,因为这些文件已被加载。
Edit : 编辑 :
Even within the plugin files, you only have access to your $_POST
values within an Ajax handler function. 即使在插件文件中,您也只能在Ajax处理程序函数中访问$_POST
值。
I recommend rethinking your goal, maybe Ajax isn't the way to go. 我建议重新考虑您的目标,也许Ajax并非可行之路。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.