[英]Wordpress AJAX, Jquery portion sends data but PHP function doesn't run
Here is the jquery portion to call the ajax function when someone clicks the a tag element. 这是当有人单击一个tag元素时调用ajax函数的jquery部分。 What I want to do is take the data value from that a tag element, pass it into the php function, and run the php function using the passed in string variable. 我想做的是从该标记元素中获取数据值,将其传递到php函数中,并使用传入的字符串变量运行php函数。 The Jquery portion works, I can send the data value, but the PHP function doesn't even run, not sure what I'm doing wrong. jQuery部分有效,我可以发送数据值,但是PHP函数甚至无法运行,不确定我在做什么错。
$(function(){
$('#catFilter a').on('click', function(e){
e.preventDefault();
$(this).fadeOut(300);
var x = $(this).attr('data-slug');
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
$.ajax({
url: ajaxurl,
type: 'post',
data: {data: x, action: 'filter'},
success: function(data, status) {
console.log(x);
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
});
And the PHP portion, I want to add the data value from the A tag element into the PHP array, and then run the function with the passed in parameters. 在PHP部分,我想将A标签元素中的数据值添加到PHP数组中,然后使用传入的参数运行该函数。
function filter(){
$x = $_POST['data'];
array_push($needleArray, $x);
post_filter();
die();
}
add_action('wp_ajax_filter', 'filter');
add_action('wp_ajax_nopriv_filter', 'filter');
Wordpress uses jQuery noConflict mode in-order to avoid conflict with other javascript libraries that may uses the symbol $. 为了避免与可能使用符号$的其他JavaScript库发生冲突,Wordpress使用jQuery noConflict模式。 You need to change from this: 您需要对此进行更改:
$(function(){
// your code
});
To this: 对此:
jQuery(function($){
// your code
});
This is the safe way to use jQuery. 这是使用jQuery的安全方法。 https://developer.wordpress.org/reference/functions/wp_enqueue_script/#user-contributed-notes https://developer.wordpress.org/reference/functions/wp_enqueue_script/#user-contributed-notes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.