0

I am currently working on a project which I am trying to call out the subcategories contents using Ajax. The Subcategories name will be listed as a menu, to call out their individual contents.

I found a tutorial here link, and start following the steps with a small tweaks. Unfortunately, I didn't get the function to work. There isn't any contents coming out after click on the subcategories name. And I received an error message saying "ReferenceError: cat_ajax_get is not defined".

And this error, I believe is referring the the below, which fall on "Code in the index.php".

<li id="cat-<?php echo $cat->term_id; ?>"><a class="<?php echo $cat->slug; ?> ajax" onclick="cat_ajax_get('<?php echo $cat->term_id; ?>');" href="#"><?php echo $cat->name; ?></a></li>

Below is the codes I have been using within my wordpress theme.

Code in the index.php -

<nav class="category-group">
    <?php
        $categories = get_categories(array('child_of' => 5));
    ?>
    <ul class="filter">
        <?php foreach($categories as $cat) { ?>
            <li id="cat-<?php echo $cat->term_id; ?>"><a class="<?php echo $cat->slug; ?> ajax" onclick="cat_ajax_get('<?php echo $cat->term_id; ?>');" href="#"><?php echo $cat->name; ?></a></li>
        <?php } ?>
    </ul>
</nav>

<div id="category-post-content"></div>

Code in the JS -

jQuery(document).ready(function($){
 function cat_ajax_get(catID) {
  $(".filter a.ajax").removeClass("selected");
  $(".filter a.ajax").addClass("selected");
  var ajaxurl = '<?php echo admin_url( "admin-ajax.php" ); ?>';
  $.ajax({
     type: 'POST',
     url: ajaxurl,
     data: {"action": "load-filter", cat: catID },
     success: function(response) {
         $("#category-post-content").html(response);
         return false;
   }
  });
 }
});

Code in functions.php -

add_action( 'wp_ajax_nopriv_load-filter', 'prefix_load_cat_posts' );
add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
function prefix_load_cat_posts () {
 $cat_id = $_POST[ 'cat' ];
 $args = array (
  'cat' => $cat_id,
  'posts_per_page' => 10
 );

 $posts = get_posts( $args );
 global $post;

 ob_start ();

 foreach ( $posts as $post ) {
 setup_postdata( $post ); ?>

 <div id="post-<?php echo $post->ID; ?>" <?php post_class(); ?>>
  <div class="article">
    <div class="article__thumbnail"><?php the_post_thumbnail();?></div>
        <div class="article__content">
            <div class="article__header"><?php the_title(); ?></div>
            <div class="article__brief"><?php the_content(); ?></div>
        </div>
    </div>
  </div>

  <?php } wp_reset_postdata();

  $response = ob_get_contents();
  ob_end_clean();

  echo $response;
  die(1);
 }

Personally, I suspect something must be wrong with the function code. Since I am calling the subcategories contents, should <'cat' = $cat_id> be something else? And in the JS code, there isn't any <'click'> command. If that's the case, how do the "class" be added in?

Can someone show me some guide or clue to make the miracle happen?

Thank you.

  • Can you update your post to include some common debugging tests? Such as if errors are in your browsers JS console, verification that your jQuery selectors select the correct item, proof your AJAX call completed ( try console.log() ), verification no PHP warnings or errors are in your PHP error log, verification $response has the output buffers contents, etc – Tom J Nowell Feb 14 '16 at 15:17
  • Also, you mentioned PHP in your index.php, this is not how AJAX in WordPress works, and implies you're running a standalone PHP file which is both a security risk and requires bootstrapping WP ( and is also incompatible with the admin-ajax.php method ) – Tom J Nowell Feb 14 '16 at 15:18
  • My apologise, I afraid I can't answer your questions, Tom. I am just a novice. If you say the way how I use the AJAX is incorrect, do you think you can show me the right way? And I also don't know how to do the console.log(). Perhaps if you can show me the way, I can then send you back the result? – Danc Chan Feb 14 '16 at 15:40
  • The javascript console.log("Hello world"); will print "Hello world" in the browsers javascript console. Open your browser dev tools and go to the console tab to see, any errors or failures will be listed there too. It's like putting echo statements in PHP to verify that code was reached etc. Also look into PHP error logging, it's a super useful and critical part of development but where your log is will depend on your host and server – Tom J Nowell Feb 14 '16 at 16:25
  • Hi Tom, the only error I saw is "ReferenceError: cat_ajax_get is not defined". And this link fall on line <a> tag. which I am going to highlight it above. – Danc Chan Feb 14 '16 at 16:39
0
onclick="cat_ajax_get(...)"

looks for a function in the global Javascript scope. This line:

jQuery(document).ready(function($){

hides everything from the global scope. So, this won't work.

You will have to use a completely different technique here. Do not set the onclick attribute. Instead attach the handler from inside your Javascript code:

jQuery(document).ready(function($){
    var links = $(".filter a.ajax");
    var ajaxurl = '<?php echo admin_url( "admin-ajax.php" ); ?>';

    function cat_ajax_get (event) {
        var catIDText = $(event.target).parent().prop('id');
        var catID = catIDText.substring(4);

        links.removeClass("selected"); // remove class from all lines
        $(event.target).addClass("selected"); // only add it back on the selected

        $.ajax({
             type: 'POST',
             url: ajaxurl,
             data: {"action": "load-filter", cat: catID },
             success: function(response) {
                 $("#category-post-content").html(response);
                 return false;
            }
        });
    }
    links.click(cat_ajax_get);
});
  • Hi ccprog, May I know how does these 2 lines work? var catIDText = $(event.target).parent().prop('id'); var catID = catIDText.substring(4); After I applied the command to another parent category, the previous contents brought forwarded... – Danc Chan Feb 15 '16 at 13:05
  • $(event.target) is the <a> element clicked on as a jQuery object, .parent() selects the enclosing <li> element, .prop('id') returns its id attribute, i. e. cat-xxxx. .substring(4) strips the cat- prefix, and you should end up with your term id. – ccprog Feb 15 '16 at 13:55
  • Thank you for the explanation. May I know is there a way I can reset the call, whenever I click on another parent category? At the moment, the previous subcategory content is showing in another category, when I click on another parent category. – Danc Chan Feb 15 '16 at 15:28
  • Let's be clear on terminology here. You have a menu with categories, and inside these categories there are subcategories? So, your code starting with <nav class="category-group"> is one of multiple entries? – ccprog Feb 15 '16 at 18:41
  • ok, every subcategories will have their own <nav class="category-group"> within the tab section. e.g: inside Tab A, I will have A1, A2, A3. Then Inside Tab B, Same thing happen. It will have B1, B2, B3. And they share the same class, and the same Ajax content holder <div id="category-post-content"></div>, but I have changed the ID to class. Hope my explanation good enough for you to understand. – Danc Chan Feb 15 '16 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.