Skip to content
Advertisement

Uncaught TypeError: Cannot read property ‘length’ of null when retrieving tags from wp

I am trying to use jquery autocomplete to retrieve tags from wordpress db

First I set a function in wp:

if ( ! function_exists( 'yourtheme_frontend_scripts' ) ) {
    function yourtheme_frontend_scripts() {

        wp_enqueue_script( 'yourtheme_custom', get_template_directory_uri().'/js/tags.js', array( 'jquery-ui-autocomplete', 'jquery' ), '1.0.0', true );

        wp_localize_script( 'yourtheme_custom', 'yourtheme_autocomplete', array(
            'autocomplete' => json_encode($results_array), // Results array contains all your autocomplete words
        ) );
    }
}

add_action( 'after_setup_theme', 'yourtheme_theme_setup' );

if ( ! function_exists( 'yourtheme_theme_setup' ) ) {
    function yourtheme_theme_setup() {

        add_action( 'wp_enqueue_scripts', 'yourtheme_frontend_scripts' );

    }
}

Then i create a js:

$(document).ready(function($) {
    "use strict";

    var autocomplete_terms = JSON.parse( yourtheme_autocomplete.autocomplete );

    var accentMap = {
        "ä": "a",
        "ö": "o",
        "å": "a",
        "č": "c"
    };

    var normalize = function( term ) {
        var ret = "";
        for ( var i = 0; i < term.length; i++ ) {
            ret += accentMap[ term.charAt(i) ] || term.charAt(i);
        }
        return ret;
    };

    $('#tags').autocomplete({
        source: function( request, response ) {
            var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
            response( $.grep( autocomplete_terms, function( value ) {
                value = value.label || value.value || value;
                return matcher.test( value ) || matcher.test( normalize( value ) );
            }) );
        }
    });

});

And finally my input:

<input class="form-control" id="tags">

But as soon as I start typing I get:

Uncaught TypeError: Cannot read property ‘length’ of null

and

at a.(EXAMPLE PATH/anonymous function).(anonymous function).source

Advertisement

Answer

This is how I resolved it:

In function php I run ajax to loop the list of my categories and check if what the user is typing is present otherwise I let him write his own:

  add_action( 'wp_footer', 'ajax_fetch' );
  function ajax_fetch() {

?>

  <script type="text/javascript">
  function fetch(){

      jQuery.ajax({
          url: '<?php echo admin_url('admin-ajax.php'); ?>',
          type: 'post',
          data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
          success: function(data) {
                var dataArray = data.split("|");
                 jQuery( "#keyword" ).autocomplete({
                  source: dataArray
                });
          }
      });

  }
  </script>

<?php
  }

add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');

function data_fetch(){
    $key = $_POST['keyword'];
    $args = array(
      'orderby' => 'id',
      'hide_empty'=> 0,
      'name__like' => $key
  );
  $categories = get_categories($args);
  foreach ($categories as $cat) {
    echo $cat->name."|";
  }
  die();
}

Then I set up an input using jquery autocomplete:

<div class="ui-widget">
  <label for="keyword">Tags: </label>
  <input id="keyword"  onkeyup="fetch()">
</div>

Note:

We need to load autocomplete and the css within wp function:

function add_scripts(){
  wp_enqueue_script( 'jquery-ui-autocomplete' );
}
add_action('wp_enqueue_scripts', 'add_scripts');

function add_stylesheet_to_head() {
  echo "<link href='https://cdnjs.cloudflare.com/ajax/libs/jquery-autocomplete/1.0.7/jquery.auto-complete.css' rel='stylesheet' type='text/css'>";
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement