Example: Search progress events using JavaScript in a template

This example uses JavaScript to retrieve the progress of a search, including the status of the search and the properties of the search job.

[example]

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 progress events (JavaScript){% endblock title %}

{% block css %}
    <style>
        .main-area {
            padding: 30px;
        }
    </style>
{% endblock css %}

{% block content %}
<div>
    <div class="main-area">
        <p>A search (<tt>index=_internal | head 50000</tt>) runs when the page is loaded. Progress is indicated here by displaying the 
        number of matching events.</p>
        <p>When the search has completed, an object 
        containing the properties of the search job is displayed in the console.</p>
        <h4><div id="progresstext">...status...</div></h4>

    </div>
</div>
{% endblock content %}

{% block js %}    
<script>
    var deps = [
        "splunkjs/ready!",
        "splunkjs/mvc/searchmanager"
    ];
    require(deps, function(mvc) {
        // Load individual components
        var SearchManager = require("splunkjs/mvc/searchmanager");

        // Create the search manager
        var mysearch = new SearchManager({
            id: "search1",
            app: "search",
            cache: false,
            search: "index=_internal | head 50000" 
        });

        mysearch.on('search:failed', function(properties) {
            // Print the entire properties object
            console.log("FAILED:", properties);
            document.getElementById("progresstext").innerHTML="Failed!";
        });

        mysearch.on('search:progress', function(properties) {
            // Print just the event count from the search job
            console.log("IN PROGRESS.\nEvents so far:", properties.content.eventCount);
            document.getElementById("progresstext").innerHTML="In progress with " + properties.content.eventCount + " events...";
        });

        mysearch.on('search:done', function(properties) {
            // Print the search job properties
            console.log("DONE!\nSearch job properties:", properties.content);
            document.getElementById("progresstext").innerHTML="Done!";
        });
    });
</script>
{% endblock js %}