Ajax action from main js only works when function is in functions.php

Hi there,

I have a feeling this might have to do with a namespace issue. But I cannot get this function to fire unless it’s in functions.php. For consistency I would like it remain in extras.php. When I move the function over to functions.php and remove namespace it works fine other wise the data returned is 0.

Here is is my JS:

filterPosts: function(){
  var ajax_url = post_filter.ajax_url;
  function getPostsCat(category){
    $.ajax({
      type: 'GET',
      url: ajax_url,
      var data: {
        action: 'post_filter', 
        category: category,
      },
      beforeSend: function (){
        //FadeOut
        var children = $('#category-post-content').children();
        children.fadeOut('slow');
      },
      success: function(data){
        //Fade in new content
        $('#category-post-content').fadeIn('slow');
        $('#category-post-content').html(data);
        console.log(data);
      },
      error: function(){
        console.log('no posts found');
      }
    }); 
  }

}

and here what’s in my extras.php

//Add Ajax Actions
add_action('wp_ajax_post_filter', __NAMESPACE__ . 'post_filter');
add_action( 'wp_ajax_nopriv_post_filter', __NAMESPACE__ . 'post_filter');

//Construct Loop & Results
function post_filter(){
  $cat_id     = $_GET['category'];
  //$posts_page = $_GET['post_page'];
  include(locate_template('templates/archive-blog.php'));
  if (isset($cat_id)) {
    die();
  };

}

You’re missing a double slash, it should be __NAMESPACE__ . '\\post_filter'

1 Like

Oh geez :expressionless: I feel like an idiot. Thank you

I spent a few hours trying to figure out the same issue until I saw this post! Thanks for providing this answer, helped me greatly.

1 Like