Example: Search results model using JavaScript in a template

This example uses JavaScript to retrieve the different types of search results from the results model: events, preview, results, and summary.


To use this code, save it as an HTML file under an existing app in $SPLUNK_HOME/etc/apps/app_name/django/app_name/templates, then view the page in Splunk. For example, to view mypage.html in mysplunkapp, go to http://localhost:8000/dj/mysplunkapp/mypage. For more about creating an app, see How to create a Web Framework app using SplunkJS Stack.

{% extends 'splunkdj:base_with_app_bar.html' %}

{% load splunkmvc %}

{% block title %}Search results model (JavaScript){% endblock title %}

{% block css %}
        .main-area {
            padding: 30px;
{% endblock css %}

{% block content %}
    <div class="main-area">
        <h3>search index=_internal | head 5</h3>
        <div id="mytable"></div>
        <h4>Results model</h4>
        <p>Select the type of results to retrieve, then look in the console to explore the <tt>data</tt> object and Backbone collection.</p>
        <div id="mydropdown">
{% endblock content %}

{% block js %}
    var deps = [
    require(deps, function(mvc) {
        // Load the components 
        var SearchManager = require("splunkjs/mvc/searchmanager");
        var TableView = require("splunkjs/mvc/tableview");
        var DropdownView = require("splunkjs/mvc/dropdownview");

        // Create the search manager and views
        var mainSearch = new SearchManager({
            id: "mysearch",
            search: "index=_internal | head 5",
            data: mvc.tokenSafe("$datamod$"),
            status_buckets: 300,
            preview: true,
            cache: false

        var table1 = new TableView({
            managerid: "mysearch",
            el: $("#mytable")

        var mydropdown = new DropdownView({
            showClearButton: false,
            value: mvc.tokenSafe("$datamod$"),
            el: $("#mydropdown")

        // Set the dropdown list choices
        var choices = [
            {label: "events",  value: "events" },
            {label: "preview", value: "preview"},
            {label: "results", value: "results"},
            {label: "summary", value: "summary"}
        mydropdown.settings.set("choices", choices);

        // Display the type of selected results model in the console
        var myChoice = "results";
        mydropdown.on("change", function(){
            myChoice = mydropdown.settings.get("value");
            var myResults = mainSearch.data(myChoice);
            myResults.on("data", function() {
                console.log("Type: ", myChoice);
                console.log("Has data? ", myResults.hasData());
                console.log("Data (rows): ", myResults.data().rows);
                console.log("Backbone collection: (rows) ", myResults.collection().raw.rows);
{% endblock js %}