[英]Call php function from js in wordpress plugin
I'm trying to pass some data from js to a PHP function in a WordPress plugin I'm currently developing, but I'm not sure if this is the way of doing it.我正在尝试将一些数据从 js 传递到我目前正在开发的 WordPress 插件中的 PHP 函数,但我不确定这是否是这样做的方式。 Essentially what I want to achieve is as follows:
基本上我想要实现的目标如下:
As it works now is that it always returns 0 and I don't know how to access the response correctly.现在它的工作原理是它总是返回 0 而我不知道如何正确访问响应。 Can anyone help me here?
有人能帮我一下吗? All of this is happening in the wp-admin area if that matters.
如果重要的话,所有这些都发生在 wp-admin 区域。 Below is the code.
下面是代码。
functions.php:函数.php:
add_action('wp_ajax_post_type_search_callback', 'my_callback');
function my_callback() {
$data= $_POST['variable'];
$output= 'i was returned with ajax';
//need to echo output and exit here ?
echo $output;
exit();
}
JS: JS:
$('#import_posts').on('click', function(e) {
$.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: 'my_callback',
variable: 45
},
success: function (output) {
$('.response').html(output);
}
});
});
HTML: HTML:
<button id="import_posts" class="button button-primary button-large">Submit</button>
<div class="response">
response
</div>
I hope this will work for you.我希望这对你有用。
You passes action in JS file "my_callback" but in PHP file there is not such a action is available.您在 JS 文件“my_callback”中传递动作,但在 PHP 文件中没有这样的动作可用。 You need to change this line.
您需要更改此行。
add_action('wp_ajax_search_callback', array($this, 'my_action_post_type_search_callback'));
Also if possible than pass dynamic path of admin-ajax.php file so you can use this file from any of you site's page.此外,如果可能,请传递 admin-ajax.php 文件的动态路径,以便您可以从任何站点页面使用此文件。 Current integration will only work for home page.
当前集成仅适用于主页。 You can get the path of the admin-ajax.php via wp's default function called
<?php echo admin_url('admin-ajax.php'); ?>
您可以通过 wp 的默认函数
<?php echo admin_url('admin-ajax.php'); ?>
获取 admin-ajax.php 的路径<?php echo admin_url('admin-ajax.php'); ?>
<?php echo admin_url('admin-ajax.php'); ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.