Harvard Extension School
CSCI E-12 Fundamentals of Web Site Development | Fall 2019

## Course Search Example - Live!

- Course Search - Live

### Data

- Base URL: `http://cscie12.dce.harvard.edu/ajax/course_search`
- Expects "keyword" parameter which is the search term and "output=json"
- Example URL:http://cscie12.dce.harvard.edu/ajax/course_search?keyword=China&output=json

### Markup (Form Part)

    <form id="course_search_form">
      <div>
          <input type="text" id="search_query" name="search_query" size="40" placeholder="Search by title, instructor, description" />
          <input type="submit" name="submit" value="Search" />
      </div>
      <div id="courselist">
          Course Listings will be updated here.
      </div>
    </form>

### JavaScript

    $(document).ready(function () {
        console.log("DOM READY!");
        var course_template_source = $('#courselisttemplate').html();
        var course_template_compiled = Handlebars.compile(course_template_source);

        console.log(course_template_source);
        console.log(course_template_compiled);

        $('#course_search_form').submit(function (e) {
            console.log("form submitted!")
            var search_term = $('#search_query').val();
            console.log("search term is: " + search_term);
            $.getJSON('/ajax/course_search', {
                    'keyword': search_term,
                    'output': 'json'
                },
                function (data) {
                    console.log("data retrieved is: ");
                    console.log(data);
                    var myresult = course_template_compiled(data);
                    $('#courselist').html(myresult);
                }
            )
            e.preventDefault();
        });
    });

### Handlebars Template

    <div id="courselisttemplate" class="handlebars">
    <p>{{courses.length}} courses were found</p>
    <ul>
        {{#courses}}
        <li class="course">
            <span class="number">{{course_group}} {{num_int}}{{num_char}}</span>
            <br/>
            <span class="title">{{title}}</span>
            <br/>
            <span class="faculty">{{faculty_text}}</span>
            <br/>
            <span class="meeting">{{meeting_text}}</span>
        </li>
        {{/courses}}
    </ul>
    </div>

Copyright © David Heitmeyer