Dashboards & Visualizations

Cannot get the input field value in search query

chrismok
Path Finder

Hi All,

As I need to get the latest record in search query. And then basic on these result to pass on each search query to generate the chart. However the system cannot declare the input field $field1$
( Please uncomment

"search": "index=_internal |stats count by sourcetype|sort + count|where count>$field1$|table sourcetype",

and comment

"search": "index=_internal |stats count by sourcetype|sort + count|where count>0|table sourcetype",

)
in "search0" SearchManager. I am not sure that is that input parameter is only available for the search query in chart.

And the other question is...... I try to handcode to declare the input as zero (You can uncomment

var input = $("#field1 input").val();
                if (input == "" || input == null)
                {
                input = 0;
                }

)

. However, when I submit the value in UI, the system will not trigger my "search0" query and generate all of the chart again. As a result, do you have any solution for solve these problem.

I created the sample HTML dashboard code for you all to try.

Thanks,
Chris

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <title>Table Element HTML | Splunk</title>
      <link rel="shortcut icon" href="{{SPLUNKWEB_URL_PREFIX}}/static/img/favicon.ico" />
      <link rel="stylesheet" type="text/css" href="{{SPLUNKWEB_URL_PREFIX}}/static/css/build/bootstrap.min.css" />
      <link rel="stylesheet" type="text/css" media="all" href="{{SPLUNKWEB_URL_PREFIX}}/static/css/build/pages/dashboard-simple-bootstrap.min.css" />
      <!--[if IE 7]>
      <link rel="stylesheet" href="{{SPLUNKWEB_URL_PREFIX}}/static/css/sprites-ie7.css" />
      <![endif]-->
   </head>
   <body class="simplexml preload locale-zh">
      <!-- 
         BEGIN LAYOUT
         This section contains the layout for the dashboard. Splunk uses proprietary
         styles in <div> tags, similar to Bootstrap's grid system. 
         -->
      <a class="navSkip" href="#navSkip" tabindex="1">Screen reader users, click here to skip the navigation bar</a>
      <div class="header">
         <div id="placeholder-splunk-bar">
            <a href="{{SPLUNKWEB_URL_PREFIX}}/app/launcher/home" class="brand" title="splunk &gt; listen to your data">splunk<strong>&gt;</strong></a>
         </div>
         <div id="placeholder-app-bar"></div>
      </div>
      <a id="navSkip"></a>
      <div class="dashboard-body container-fluid main-section-body" data-role="main">
         <div class="dashboard-header clearfix">
            <h2>Table Element HTML</h2>
            <p class="description"></p>
         </div>
         <div class="fieldset">
            <div class="input input-text" id="field1">

            </div>
        <div class="panel-body" id="view_checkboxgroup">
                    </div>
         </div>
          <div class="dashboard-row dashboard-row0">
            <div class="dashboard-element chart" id="element0" style="width: 100%">
            </div>
        </div>
         <div class="dashboard-row dashboard-row1">
            <div class="dashboard-cell" style="width: 100%;">
               <div class="dashboard-panel clearfix">
                  <div class="panel-element-row">
                     <div class="dashboard-element chart" id="element1" style="width: 100%">
                        <div class="panel-head">
                           <h3>Top 1</h3>
                        </div>
                        <div class="panel-body"></div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
         <div class="dashboard-row dashboard-row2">
            <div class="dashboard-cell" style="width: 100%;">
               <div class="dashboard-panel clearfix">
                  <div class="panel-element-row">
                     <div class="dashboard-element chart" id="element2" style="width: 100%">
                        <div class="panel-head">
                           <h3>Top 2</h3>
                        </div>
                        <div class="panel-body"></div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
         <div class="dashboard-row dashboard-row3">
            <div class="dashboard-cell" style="width: 100%;">
               <div class="dashboard-panel clearfix">
                  <div class="panel-element-row">
                     <div class="dashboard-element chart" id="element3" style="width: 100%">
                        <div class="panel-head">
                           <h3>Top 3</h3>
                        </div>
                        <div class="panel-body"></div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
      <div class="footer"></div>
      <!-- 
         END LAYOUT
         -->
      <script src="{{SPLUNKWEB_URL_PREFIX}}/config?autoload=1"></script>
      <script src="{{SPLUNKWEB_URL_PREFIX}}/static/js/i18n.js"></script>
      <script src="{{SPLUNKWEB_URL_PREFIX}}/i18ncatalog?autoload=1"></script>
      <script src="{{SPLUNKWEB_URL_PREFIX}}/static/js/build/simplexml.min/config.js"></script>
      <script type="text/javascript">
         require.config({
             baseUrl: "{{SPLUNKWEB_URL_PREFIX}}/static/js",
             waitSeconds: 0 // Disable require.js load timeout
         });

         //
         // LIBRARY REQUIREMENTS
         //
         // In the require function, we include the necessary libraries and modules for
         // the HTML dashboard. Then, we pass variable names for these libraries and
         // modules as function parameters, in order.
         // 
         // When you add libraries or modules, remember to retain this mapping order
         // between the library or module and its function parameter. You can do this by
         // adding to the end of these lists, as shown in the commented examples below.

         require([
             "splunkjs/mvc",
             "splunkjs/mvc/utils",
             "splunkjs/mvc/tokenutils",
             "underscore",
             "jquery",
             "splunkjs/mvc/simplexml",
             "splunkjs/mvc/headerview",
             "splunkjs/mvc/footerview",
             "splunkjs/mvc/simplexml/dashboardview",
             "splunkjs/mvc/simplexml/element/chart",
             "splunkjs/mvc/simplexml/element/event",
             "splunkjs/mvc/simplexml/element/html",
             "splunkjs/mvc/simplexml/element/list",
             "splunkjs/mvc/simplexml/element/map",
             "splunkjs/mvc/simplexml/element/single",
             "splunkjs/mvc/simplexml/element/table",
             "splunkjs/mvc/simpleform/formutils",
             "splunkjs/mvc/simpleform/input/dropdown",
             "splunkjs/mvc/simpleform/input/radiogroup",
             "splunkjs/mvc/simpleform/input/multiselect",
             "splunkjs/mvc/simpleform/input/checkboxgroup",
             "splunkjs/mvc/simpleform/input/text",
             "splunkjs/mvc/simpleform/input/timerange",
             "splunkjs/mvc/simpleform/input/submit",
             "splunkjs/mvc/searchmanager",
             "splunkjs/mvc/savedsearchmanager",
             "splunkjs/mvc/postprocessmanager",
             "splunkjs/mvc/simplexml/urltokenmodel"
             // Add comma-separated libraries and modules manually here, for example:
             // ..."splunkjs/mvc/simplexml/urltokenmodel",
             // "splunkjs/mvc/checkboxview"
             ],
             function(
                 mvc,
                 utils,
                 TokenUtils,
                 _,
                 $,
                 DashboardController,
                 HeaderView,
                 FooterView,
                 Dashboard,
                 ChartElement,
                 EventElement,
                 HtmlElement,
                 ListElement,
                 MapElement,
                 SingleElement,
                 TableElement,
                 FormUtils,
                 DropdownInput,
                 RadioGroupInput,
                 MultiSelectInput,
                 CheckboxGroupInput,
                 TextInput,
                 TimeRangeInput,
                 SubmitButton,
                 SearchManager,
                 SavedSearchManager,
                 PostProcessManager,
                 UrlTokenModel

                 // Add comma-separated parameter names here, for example: 
                 // ...UrlTokenModel, 
                 // CheckboxView
                 ) {



                 var pageLoading = true;


                 // 
                 // TOKENS
                 //

                 // Create token namespaces


                 var urlTokenModel = new UrlTokenModel();
                 mvc.Components.registerInstance('url', urlTokenModel);
                 var defaultTokenModel = mvc.Components.getInstance('default', {create: true});
                 var submittedTokenModel = mvc.Components.getInstance('submitted', {create: true});

                 urlTokenModel.on('url:navigate', function() {
                     defaultTokenModel.set(urlTokenModel.toJSON());
                     if (!_.isEmpty(urlTokenModel.toJSON()) && !_.all(urlTokenModel.toJSON(), _.isUndefined)) {
                         submitTokens();
                     } else {
                         submittedTokenModel.clear();
                     }
                 });

                 // Initialize tokens
                 defaultTokenModel.set(urlTokenModel.toJSON());

                 function submitTokens() {
                     // Copy the contents of the defaultTokenModel to the submittedTokenModel and urlTokenModel
                     FormUtils.submitForm({ replaceState: pageLoading });
                 }

                 function setToken(name, value) {
                     defaultTokenModel.set(name, value);
                     submittedTokenModel.set(name, value);
                 }

                 function unsetToken(name) {
                     defaultTokenModel.unset(name);
                     submittedTokenModel.unset(name);
                 }


                  //
                 // VIEWS: FORM INPUTS
                 //
                 var field1 = new TextInput({
                     "id": "field1",
                     "default": "0",
                     "searchWhenChanged": true,
                     "value": "$form.field1$",
                     "el": $('#field1')
                 }, {tokens: true}).render();

                 field1.on("change", function(newValue) {
                     FormUtils.handleValueChange(field1);
                 });

            /*  
                var input = $("#field1 input").val();
                if (input == "" || input == null)
                {
                input = 0;
                }
                */

                 var search0 = new SearchManager({
                     "id": "search0",
                     "cancelOnUnload": true,
                     "status_buckets": 0,
                     "earliest_time": "-24h@h",
       //"search": "index=_internal |stats count by sourcetype|sort + count|where count>"+input+"|table sourcetype",
        //"search": "index=_internal |stats count by sourcetype|sort + count|where count>$field1$|table sourcetype",
        "search": "index=_internal |stats count by sourcetype|sort + count|where count>0|table sourcetype",
                     "latest_time": "now",
                     "app": utils.getCurrentApp(),
                     "auto_cancel": 90,
                     "preview": true,
                     "runWhenTimeIsUndefined": false
                 }, {tokens: true, tokenNamespace: "submitted"});

                 var a = [];


                    search0.on("search:done", function(state, job) {
                            if (state.content.resultCount === 0) {
                            alert("no results");
                            }
                    });

                 var r = search0.data('results');

                    r.on('data', function(results) {

                     for (var n = 0; n <= r.data().rows.length - 1; n++) {

                         a.push(r.data().rows[n][0]);
                         console.log(r.data().rows[n][0]);
                     }

                 //
                 // SEARCH MANAGERS
                 //



                 var search1 = new SearchManager({
                     "id": "search1",
                     "cancelOnUnload": true,
                     "status_buckets": 0,
                     "earliest_time": "-24h@h",
        "search": "index=_internal  sourcetype="+a[0]+"|stats count by sourcetype|head 10",

                     "latest_time": "now",
                     "app": utils.getCurrentApp(),
                     "auto_cancel": 90,
                     "preview": true,
                     "runWhenTimeIsUndefined": false
                 }, {tokens: true, tokenNamespace: "submitted"});
                console.log("Break!!!!!");
                 var search2 = new SearchManager({
                     "id": "search2",
                     "cancelOnUnload": true,
                     "status_buckets": 0,
                     "earliest_time": "-24h@h",
                     "search": "index=_internal  sourcetype="+a[1]+"|stats count by sourcetype|head 10",

                     "latest_time": "now",
                     "app": utils.getCurrentApp(),
                     "auto_cancel": 90,
                     "preview": true,
                     "runWhenTimeIsUndefined": false
                 }, {tokens: true, tokenNamespace: "submitted"});

                 var search3 = new SearchManager({
                     "id": "search3",
                     "cancelOnUnload": true,
                     "status_buckets": 0,
                     "earliest_time": "-24h@h",
                     "search": "index=_internal  sourcetype="+a[2]+"|stats count by sourcetype|head 10",

                     "latest_time": "now",
                     "app": utils.getCurrentApp(),
                     "auto_cancel": 90,
                     "preview": true,
                     "runWhenTimeIsUndefined": false
                 }, {tokens: true, tokenNamespace: "submitted"});



                 //
                 // SPLUNK HEADER AND FOOTER
                 //

                 new HeaderView({
                     id: 'header',
                     section: 'dashboards',
                     el: $('.header'),
                     acceleratedAppNav: true,
                     useSessionStorageCache: true
                 }, {tokens: true}).render();

                 new FooterView({
                     id: 'footer',
                     el: $('.footer')
                 }, {tokens: true}).render();


                 //
                 // DASHBOARD EDITOR
                 //

                 new Dashboard({
                     id: 'dashboard',
                     el: $('.dashboard-body')
                 }, {tokens: true}).render();


                 //
                 // VIEWS: VISUALIZATION ELEMENTS
                 //

                 var element1 = new ChartElement({
                     "id": "element1",
                     "dataOverlayMode": "none",
                     "charting.axisY.scale": "linear",
                     "charting.chart.nullValueMode": "gaps",
                     "charting.layout.splitSeries": "0",
                     "charting.axisLabelsX.majorLabelStyle.rotation": "0",
                     "charting.axisTitleX.visibility": "visible",
                     "count": "10",
                     "charting.axisX.scale": "linear",
                     "charting.chart.sliceCollapsingThreshold": "0.01",
                     "rowNumbers": "true",
                     "charting.legend.placement": "right",
                     "resizable": true,
                     "charting.axisTitleY2.visibility": "visible",
                     "charting.chart.style": "shiny",
                     "charting.axisTitleY.visibility": "visible",
                     "wrap": "true",
                     "charting.axisY2.scale": "inherit",
                     "charting.legend.labelStyle.overflowMode": "ellipsisMiddle",
                     "charting.chart": "pie",
                     "charting.chart.stackMode": "default",
                     "charting.drilldown": "all",
                     "charting.axisY2.enabled": "false",
                     "charting.axisLabelsX.majorLabelStyle.overflowMode": "ellipsisNone",
                     "managerid": "search1",
                     "el": $('#element1')
                 }, {tokens: true}).render();


                 var element2 = new ChartElement({
                     "id": "element2",
                     "dataOverlayMode": "none",
                     "charting.axisY.scale": "linear",
                     "charting.chart.nullValueMode": "gaps",
                     "charting.layout.splitSeries": "0",
                     "charting.axisLabelsX.majorLabelStyle.rotation": "0",
                     "charting.axisTitleX.visibility": "visible",
                     "count": "10",
                     "charting.axisX.scale": "linear",
                     "charting.chart.sliceCollapsingThreshold": "0.01",
                     "rowNumbers": "true",
                     "charting.legend.placement": "right",
                     "resizable": true,
                     "charting.axisTitleY2.visibility": "visible",
                     "charting.chart.style": "shiny",
                     "charting.axisTitleY.visibility": "visible",
                     "wrap": "true",
                     "charting.axisY2.scale": "inherit",
                     "charting.legend.labelStyle.overflowMode": "ellipsisMiddle",
                     "charting.chart": "pie",
                     "charting.chart.stackMode": "default",
                     "charting.drilldown": "all",
                     "charting.axisY2.enabled": "false",
                     "charting.axisLabelsX.majorLabelStyle.overflowMode": "ellipsisNone",
                     "managerid": "search2",
                     "el": $('#element2')
                 }, {tokens: true}).render();


                 var element3 = new ChartElement({
                     "id": "element3",
                     "dataOverlayMode": "none",
                     "charting.axisY.scale": "linear",
                     "charting.chart.nullValueMode": "gaps",
                     "charting.layout.splitSeries": "0",
                     "charting.axisLabelsX.majorLabelStyle.rotation": "0",
                     "charting.axisTitleX.visibility": "visible",
                     "count": "10",
                     "charting.axisX.scale": "linear",
                     "charting.chart.sliceCollapsingThreshold": "0.01",
                     "rowNumbers": "true",
                     "charting.legend.placement": "right",
                     "resizable": true,
                     "charting.axisTitleY2.visibility": "visible",
                     "charting.chart.style": "shiny",
                     "charting.axisTitleY.visibility": "visible",
                     "wrap": "true",
                     "charting.axisY2.scale": "inherit",
                     "charting.legend.labelStyle.overflowMode": "ellipsisMiddle",
                     "charting.chart": "pie",
                     "charting.chart.stackMode": "default",
                     "charting.drilldown": "all",
                     "charting.axisY2.enabled": "false",
                     "charting.axisLabelsX.majorLabelStyle.overflowMode": "ellipsisNone",
                     "managerid": "search3",
                     "el": $('#element3')
                 }, {tokens: true}).render();





                 // Initialize time tokens to default
                 if (!defaultTokenModel.has('earliest') && !defaultTokenModel.has('latest')) {
                     defaultTokenModel.set({ earliest: '0', latest: '' });
                 }

                 if (!_.isEmpty(urlTokenModel.toJSON())){
                     submitTokens();
                 }



                 //
                 // DASHBOARD READY
                 //

                 DashboardController.ready();
                 pageLoading = false;


         });
         }

         );
      </script>
   </body>
</html>
Tags (1)
0 Karma
1 Solution

chrismok
Path Finder

Hi all,

I found the other solution which add the result to the table in dashboard and use hidden this specific div, and system can pass the input parameter to this search query.

View solution in original post

0 Karma

chrismok
Path Finder

Hi all,

I found the other solution which add the result to the table in dashboard and use hidden this specific div, and system can pass the input parameter to this search query.

0 Karma
Get Updates on the Splunk Community!

Webinar Recap | Revolutionizing IT Operations: The Transformative Power of AI and ML ...

The Transformative Power of AI and ML in Enhancing Observability   In the realm of IT operations, the ...

.conf24 | Registration Open!

Hello, hello! I come bearing good news: Registration for .conf24 is now open!   conf is Splunk’s rad annual ...

ICYMI - Check out the latest releases of Splunk Edge Processor

Splunk is pleased to announce the latest enhancements to Splunk Edge Processor.  HEC Receiver authorization ...