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. 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. Can anyone help me here? All of this is happening in the wp-admin area if that matters. Below is the code.
functions.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:
$('#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:
<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. 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. 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'); ?>
<?php echo admin_url('admin-ajax.php'); ?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.