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:
- Send a post or get via js when clicking a button.
- In PHP, if that post/get has no error, call a function. and show an "OK"-response message.
- It has error show an "error"-response message.
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>
//do i need this?– yes, you do - but with different values, because right now the function/method name you are specifying there, does not match that of your actual function. If you don’t know how the WordPress hook / filter system works to begin with, you should go and properly read up on that first.my_callback()function to be executed. Therefore no output will be created.array($this, 'my_callback')is wrong, you are not trying to call a static method of some class here, you have just a plain function. So this needs to be just'my_callback'- no $this, no array.