Search code examples
jqueryajaxwordpressbackbone.jsbackbone-views

Uncaught TypeError: Cannot read property 'getJSON' of undefined


I am customizing a wordpress theme, Why am I getting this error when I'm trying to type in input field of search box, my html code is

<div class="mysearchdiv">
<input type="" name="" class="mysearch">
<ul class="skills-list" id="skills_list"></ul>
</div>

and backbone.js code is

jQuery(document).ready(function(){
    var mymodel= Backbone.Model.extend({
        defaults:function(){
            return{
            name:''
            }
        }
    });

    var mycollection=Backbone.Collection.extend({
        model:mymodel
    });
    var mynewcollection= new mycollection();
    var myview=Backbone.View.extend({
        model:mynewcollection,
        el:'.mysearchdiv',
        events:{
            'keypress .mysearch':'search'
        },
        initialize:function(){
            console.log("init");
            var view=this;
            this.skill_list=this.$('ul.skill-list');
            view.skills={};
            this.$el.find('input.mysearch').typeahead({
                minLength:0,
                items:10,
                source: function(query, process) {
                    console.log("Skill_Control typeahead source");
                    console.log(query);
                    console.log(process);
                    console.log(ae_globals.ajaxURL);
                    if (view.skills.length > 0) return view.skills;
//getting error at this point
//where ae_globals.ajaxURL is ajax url in wp
                    return $.getJSON(ae_globals.ajaxURL, {
                        action: 'fre_get_user_skills',
                        query: query
                    }, function(data) {

                        view.skills = data;
                        return process(data);
                    }
                    );
                },
                updater:function(item){
                    console.log("updater");
                }
            });

        },

        search:function(){
            console.log("search");
        }

    });
    new myview;
    console.log("starting");
});

The same type of code is working for me in other theme but right now i totally stuck at this point. Any help would be appreciate. Thanks in advance.


Solution

  • This is a common problem with the WordPress Environment. The $ isn't in the global scope. Either do:

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

    Or use:

    jQuery.getJSON(...