0

I am trying to get the AJAX filter to work in Wordpress but I keep getting an error:

Uncaught ReferenceError: reports is not defined filter.js?ver=1.0:5

This is the plugin that I use to enqueue the script and localize it:

ajax-filter.php

 function ajax_test_enqueue_scripts() {
    wp_enqueue_script( 'reports', plugins_url( '/js/filter.js', __FILE__ ), array('jquery'), '1.0', true );

  wp_localize_script( 'reports', 'filters',
          array(
              'ajax_filter' => admin_url( 'admin-ajax.php' ),
  ));

 }
 add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' );

And this is the .js file that it enqueues

filter.js

$( document ).ready(function() {
  $("input:checkbox").on( "change", function() {
        console.log($('input[name="filter[]"]:checked').serialize());
        jQuery.ajax({
        url : reports.ajax_filter,
        type : 'post',
        data : {
            action : 'filter_reports',
            filter : options
        },
        success : function( response ) {
            alert(response)
        }
    });
});
});

This is the page where the filtering has to be done.

page-home.php

<?php /* Template Name: Home Page */

get_header(); ?>

<header class="entry-header">
    <?php get_the_title( '<h1 class="entry-title">', '</h1>' ); ?>
</header><!-- .entry-header -->

<div class="ewf-row">
            <div style="float:left; width:100%;">
                <h1>
                Welcome <?php global $current_user;
                  get_currentuserinfo();

                  echo $current_user->display_name . "\n"; echo '<small style="font-size:12px;">' . $current_user->user_email . "\n" . '</small>'
                        ?>
                </h1>
            </div>
            <p>

<br>
<br>
<strong id="desktop-only">1 Way to access your reports</strong>
<strong id="mobile-only">2 Ways to access your reports</strong>
            </p>

            <p>
                <div id="ebook-btn-info" class="ebook-buttons-info">
                    <div class="box">
                        <div class="ebook-download-info">View</div>
                        <div style="margin-top: 8px;">Click this option if you want to download and view the report(s) as a regular PDF document.</div>
                    </div>
                    <div class="box" id="mobile-only">
                        <div class="ebook-download-info">EPUB</div>
                        <div style="margin-top: 8px;">Use the EPUB option if you want to install the report in the iBook or Kiosk app on your tablet or smartphone.</div>
                    </div>
                </div>
            </p>
            <div class="devider"></div>
        </br>

    <!--
<div id="ebooks-category">
    <div class="ebooks-category-title">Categories: </div>
    <a class="ebooks-active">EPIC</a>   <a href="http://epic.trmoncology.com/ebooks/#ebook-btn-info">EPIC - CC</a>

</div>

-->





<?php
 $disease = get_terms( array('disease') );
 $report    = get_terms( array('type')      );

?>

<div style="width:100%; float:left;"><strong>Reports currently available to you</strong></div>
<div class="devider"></div>

<div id="epic-filter">


    <h3>Disease Type</h3>
    <form name="disease" id="filter-disease">

        <?php
        foreach ($disease as $value) {
            echo '<div class="filter '.$value->slug.'">';
            echo '<input type="checkbox" data-filter=".'. $value->slug .'" class="'. $value->term_id .'" value="'. $value->term_id .'" name="filter[]" ><div class="filter-title">'. $value->name .'</div><span class="filter-count">'. $value->count .'</span>';
            echo '</div>';
            // echo $value->name;
        }
        ?>
    </form>

</div>




<!--Loop EPIC-->

<div id="ebook-wrapper">




<?php
$uid = get_current_user_id();

            //$user_cats = get_user_meta( $uid, 'categories', false );  // this should return the values as array

            $paged = ( get_query_var( 'page' ) ) ? get_query_var( 'page' ) : 1;

            $customer_account  = get_field('customer_account', 'user_'.$uid );

            $args = array(
                'post_type' => 'ebooks',
                'tax_query' => array(
                    'relation' => 'AND',
                    array(
                        'taxonomy' => 'customer',
                        'field'    => 'term_id',
                        'terms'    => $customer_account,
                    )
                ),
            );


            $the_query = new WP_Query( $args );

        // The Loop
        if ( $the_query->have_posts() ) {

            while ( $the_query->have_posts() ) {
                $the_query->the_post();

                $terms = wp_get_post_terms($post->ID, 'disease');
                foreach($terms as $term){
                ?>


            <!--Ebook Container-->

            <div id="post-<?php the_ID(); ?>" <?php post_class('ebook-container'); ?> <?php echo 'data-cat="'. $term->slug .'"' ?>>

                <!-- <div class="ebook-date"><--?php the_time('M j') ?></div> -->
                        <!-- <a href="<--?php echo get_post_permalink ( $post->ID ); ?>"></a> -->

                        <!--Image-->
                        <div class="ebook-image">
                            <img src="<?php echo the_field('e-image'); ?>"> <!--This will get the featured Image attached -->
                        </div>

                        <div id="ebook-middle">
                        <!-- Title -->
                        <div class="ebook-title">
                            <?php echo the_field('e_detail_title'); ?>
                        </div>

                </div>



                <!--Content-->
                <div class="ebook-content">
                    <?php echo the_field('e-detail-intro') ?>
                </div>

            <!--Details-->
            <div id="ebook-details">
            <div class="e-detail ebook-details-chair"><strong>Chair: </strong><?php echo the_field('e-detail-chair'); ?></div>
            <div class="e-detail ebook-details-date"><strong>Date:</strong> <?php echo the_field('e-detail-date'); ?></div>
            <div class="e-detail ebook-details-location"><strong>Location:</strong> <?php echo the_field('e-detail-location'); ?></div>
            </div>



                <div class="ebook-buttons">
                    <a href="<?php echo the_field('e-down-view'); ?>"><div class="ebook-download">View</div></a>
                    <a id="mobile-only" href="<?php echo the_field('e-pub'); ?>" download><div class="ebook-download">EPUB</div></a>
                </div>


                <!-- <?php
                if ( current_user_can('administrator') ) {
                     echo the_taxonomies( 'before=<ul>&after=</ul>' );
                } else {
                     echo "";
                }
                  ?> -->


            </div>

            <?php }} ?>

            <?php
            /* Restore original Post Data */
            wp_reset_postdata();
        } else {
            echo '<div class="alert alert-danger" role="alert">No Ebooks available.</div>';
        }
        ?>
</div>
<!--Loop EPIC - END-->

        <!-- <ul class="pagination pull-right">
            <li class="pagination-prev"><--?php echo get_previous_posts_link( 'Previous Ebook List' ); ?></li>
                        <li class="pagination-next"><--?php echo get_next_posts_link( 'Next Ebook List', $the_query->max_num_pages ); ?></li>
                        <li class="pagination-viewall"><a href="http://local.ebooks.com/ebooks/">View All Ebooks</a></li>
        </ul> -->
    </div><!-- .content-area -->

<script>


</script>

<?php get_footer(); ?>

I really hope that you guys can help me.

I already looked up a solution but I cannot find anything that is related to my code.

1

In the way you are using wp_localize_script(), the object's name is filters, not reports; so, in filter.js you should use filters.ajax_filter. Also, you should define the variable options before use it.

$( document ).ready(function() {
  $("input:checkbox").on( "change", function() {
        console.log($('input[name="filter[]"]:checked').serialize());
        jQuery.ajax({
            url : filters.ajax_filter,
            type : 'post',
            data : {
                action : 'filter_reports',
                // You should define options var before use it
                // filter : options
            },
            success : function( response ) {
                alert(response)
            }
        });
  });
});

I suggest you to use more explicit names for the variables; choose names that explain themselves; of course that is just a opinion. For example:

// Use the name of the script as handle parameter
wp_enqueue_script( 'filter', plugins_url( '/js/filter.js', __FILE__ ), array('jquery'), '1.0', true );

// Use a name for the object which explain that it is data for filter script
wp_localize_script( 'filter', 'filter_data',
          array(
              // Use a nanme that explain what the property contains
              'ajax_url' => admin_url( 'admin-ajax.php' ),
          )
);

Then, in filter.js you must use filter_data.ajax_url:

$( document ).ready(function() {
  $("input:checkbox").on( "change", function() {
        console.log($('input[name="filter[]"]:checked').serialize());
        jQuery.ajax({
            url : filter_data.ajax_url,
            type : 'post',
            data : {
                action : 'filter_reports',
                // You should define options var before use it
                // filter : options
            },
            success : function( response ) {
                alert(response)
            }
        });
  });
});
  • now i am gettting this: Uncaught ReferenceError: options is not defined – Dionoh Jan 9 '17 at 9:08
  • That is because this part of the code filter : options. Note that options is not defined anywhere in your code and that is what the error message says. What it should be? Can you explain it? There is not reference to options in your question nor in your code, so I can not know what it should be. – cybmeta Jan 9 '17 at 9:12
  • what do you mean? – Dionoh Jan 9 '17 at 9:58
  • In your code, you have a reference to a variable named options but you have not defined that variable before you try to use it; that is why you get the reference error message, and the message explains itself the problem: "options is not defined". It is simple, you have to define a variable before use it. I don't know how to explain it better. If you don't understand this, try to search about "Defining variables in JavaScript", you will find a lot of information. If you have questions about JavaScript, StackOverflow is a good place to get help. – cybmeta Jan 9 '17 at 10:05

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.