Call php function from js in wordpress plugin-ThrowExceptions

Exception or error:

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:

  1. Send a post or get via js when clicking a button.
  2. In PHP, if that post/get has no error, call a function. and show an “OK”-response message.
  3. 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.


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;


$('#import_posts').on('click', function(e) {
    type: "POST",
    url: "/wp-admin/admin-ajax.php",
    data: {
      action: 'my_callback',
      variable: 45
    success: function (output) {


  <button id="import_posts" class="button button-primary button-large">Submit</button>
  <div class="response">
How to solve:

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'); ?>

Leave a Reply

Your email address will not be published. Required fields are marked *