views:

40

answers:

1

I'm trying to copy the Google image search from this page. Here is my code:

<script type="text/javascript">
    <% if @note.text == "" %>
        google.load("search", "1",{"callback":searchCallback()});
    <% else %>
        google.load("visualization", "1",{"callback":dummyFunction});
    <% end %>

    function se() {
        var sFormDiv = document.getElementById("searchForm");
        var leftScDiv = document.getElementById("leftSearchControl");

        this.leftControl = new google.search.SearchControl();
        this.searchForm = new google.search.SearchForm(true, sFormDiv);

        this.searchForm.setOnSubmitCallback(this, se.prototype.onSubmit);
        this.searchForm.setOnClearCallback(this, se.prototype.onClear);

        this.leftControl.setResultSetSize(GSearch.LARGE_RESULTSET);

        var searcher;
        var options;

        this.leftControl.addSearcher(new google.search.ImageSearch());

        var drawOptions = new google.search.DrawOptions();
        drawOptions.setDrawMode(GSearchControl.DRAW_MODE_TABBED);

        this.leftControl.setNoResultsString(GSearchControl.NO_RESULTS_DEFAULT_STRING);

        this.leftControl.draw(leftScDiv);

        this.searchForm.execute("Ferrari");

    }

    // when the form fires a submit, grab its
    // value and call the left and right control
    se.prototype.onSubmit = function(form) {
      var q = form.input.value;
      if (q && q!= "") {
        this.leftControl.execute(q);
      }
      return false;
    }

    // when the form fires a clear, call the left and right control
    se.prototype.onClear = function(form) {
      this.leftControl.clearAllResults();
      form.input.value = "";
      return false;
    }

    function searchCallback(){
        new se();
    }

    function dummyFunction() {
    }

</script>

When I run it, I get this error:

google.search is undefined
this.leftControl = new google.search.SearchControl(); 

How can this be, if I'm getting to that line by way of the callback that is run when the search API is loaded? Thanks for reading.

+2  A: 

How can this be, if I'm getting to that line by way of the callback that is run when the search API is loaded? Thanks for reading.

You are not passing a callback, but invoking the function immediately by putting () after it. searchCallback() in turn calls se() which tries to call google.search.SearchControl, but google.search is undefined at this point, and calling any property or function on undefined will throw a TypeError.

Replace

google.load("search", "1",{"callback":searchCallback()});

with

google.load("search", "1",{"callback":searchCallback});
Anurag
Thanks so much!
ben