Hello all,
In the HTML I have included a SEARCH and set the data result in a TOKEN through the below:
var search1 = new SearchManager({
"id": "search1",
"earliest_time": "-15m@m",
"sample_ratio": null,
"cancelOnUnload": true,
"latest_time": "now",
"search": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"status_buckets": 0,
"app": utils.getCurrentApp(),
"auto_cancel": 90,
"preview": true,
"runWhenTimeIsUndefined": false
}, {tokens: true, tokenNamespace: "submitted"});
new SearchEventHandler({
managerid: "search1",
event: "finalized",
conditions: [
{
attr: "any",
value: "*",
actions: [
{"type": "set", "token": "status_execucao", "value": "$result.data_range$"}
]
}
]
});
Now I am trying to retrieve the value of this token in the JS via jQuery but am not able to do that.
Which command should I use to retrieve the token via jQuery?
$('#status_execucao').get()
?
Many thanks and regards,
Danillo Pavan
@danillopavan, first off, which version of Splunk are you on?
finalized
search event handler was used in Splunk versions 6.4 and before. Post 6.5 you should use done instead:
event: "done",
Option 1: If the token status_execucao
is already set by the time your JavaScript code tries to access the token, then depending on token model (default
or submitted
) you can use Splunk JS stack to get
and set
tokens (http://dev.splunk.com/view/webframework-developapps/SP-CAAAEW3).
// Access the "default" token model
var defaultTokenModel = mvc.Components.get("default");
// Retrieve the value of a token $status_execucao$
var tokenValue = defaultTokenModel.get("status_execucao");
Option 2: You can use Splunk JS stack to get the token value in JavaScript using token change()
event (http://dev.splunk.com/view/SP-CAAAEW4):
// Access the "default" token model
var defaultTokenModel = mvc.Components.get("default");
defaultTokenModel.on("change:status_execucao", function(newTokenName, status_execucao, options) {
if(status_execucao!==undefined && status_execucao!=="$result.data_range$"){
console.log("status_execucao: ",status_execucao);
}
});
Please try out and confirm!
Hello Niketnilay,
thanks for your support. I have tried to use the commands however it is appearing the error message:
Uncaught TypeError: Cannot read property 'get' of undefined
I have included the below dependencies:
require(['jquery','splunkjs/mvc','backbone'], function($) {
and the commands:
var mvc = require("splunkjs/mvc");
var defaultTokenModel = mvc.Components.get("default");
@danillopavan, are you using HTML dashboard or Simple XML JavaScript extension? As per your question it seemed like you are using HTML Dashboard which implies mvc
should already be included.
Here is one of my previous answers for Option 1: https://answers.splunk.com/answers/580205/how-to-get-search-idjobsid-from-xml-dashboard-in-j.html
And here is a recent answer for Option 2: https://answers.splunk.com/answers/612296/how-to-change-the-header-color-dynamically-using-j.html#an...
Following is a run anywhere example of HTML Dashboard similar to the one described by you
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Splunk Answers 612600 - Token in JavaScript HTML</title>
<link rel="shortcut icon" href="/en-US/static/@C9557AB367E3A59ED9840F5616383BD13B651EF2B463EB6C7F025F5CAFE14161/img/favicon.ico" />
<link rel="stylesheet" type="text/css" href="{{SPLUNKWEB_URL_PREFIX}}/static/build/css/bootstrap-enterprise.css" />
<link rel="stylesheet" type="text/css" href="{{SPLUNKWEB_URL_PREFIX}}/static/css/build/pages/dashboard-simple-bootstrap.min.css" />
<meta name="referrer" content="never" />
<meta name="referrer" content="no-referrer" />
<script>
window._splunk_metrics_events = {
push : function() {},
active: false,
}
</script>
</head>
<body class="simplexml preload locale-en" data-splunk-version="7.0.1" data-splunk-product="enterprise">
<!--
BEGIN LAYOUT
This section contains the layout for the dashboard. Splunk uses proprietary
styles in <div> tags, similar to Bootstrap's grid system.
-->
<header>
<a class="navSkip" href="#navSkip" tabindex="1">Screen reader users, click here to skip the navigation bar</a>
<div class="header splunk-header">
<div id="placeholder-splunk-bar">
<a href="{{SPLUNKWEB_URL_PREFIX}}/app/launcher/home" class="brand" title="splunk > listen to your data">splunk<strong>></strong></a>
</div>
<div id="placeholder-app-bar"></div>
</div>
<a id="navSkip"></a>
</header>
<div class="dashboard-body container-fluid main-section-body" data-role="main">
<div class="dashboard-header clearfix">
<h2>Token in JavaScript HTML</h2>
</div>
<div id="row1" class="dashboard-row dashboard-row1">
<div id="panel1" class="dashboard-cell" style="width: 100%;">
<div class="dashboard-panel clearfix">
<div class="panel-element-row">
<div id="element1" class="dashboard-element table" style="width: 100%">
<div class="panel-body"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--
END LAYOUT
-->
<script src="{{SPLUNKWEB_URL_PREFIX}}/config?autoload=1" crossorigin="use-credentials"></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/build/simplexml/index.js"></script>
<script type="text/javascript">
// <![CDATA[
// <![CDATA[
//
// 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/layoutview",
"splunkjs/mvc/simplexml/dashboardview",
"splunkjs/mvc/simplexml/dashboard/panelref",
"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/simplexml/element/visualization",
"splunkjs/mvc/simpleform/formutils",
"splunkjs/mvc/simplexml/eventhandler",
"splunkjs/mvc/simplexml/searcheventhandler",
"splunkjs/mvc/simpleform/input/dropdown",
"splunkjs/mvc/simpleform/input/radiogroup",
"splunkjs/mvc/simpleform/input/linklist",
"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/tokenforwarder"
],
function(
mvc,
utils,
TokenUtils,
_,
$,
DashboardController,
LayoutView,
Dashboard,
PanelRef,
ChartElement,
EventElement,
HtmlElement,
ListElement,
MapElement,
SingleElement,
TableElement,
VisualizationElement,
FormUtils,
EventHandler,
SearchEventHandler,
DropdownInput,
RadioGroupInput,
LinkListInput,
MultiSelectInput,
CheckboxGroupInput,
TextInput,
TimeRangeInput,
SubmitButton,
SearchManager,
SavedSearchManager,
PostProcessManager,
UrlTokenModel
// Add comma-separated parameter names here, for example:
// ...UrlTokenModel,
// TokenForwarder
) {
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);
}
//
// SEARCH MANAGERS
//
var search1 = new SearchManager({
"id": "search1",
"search": "index=\"_internal\" sourcetype=\"splunkd\" log_level!=\"INFO\" | stats count as Errors",
"latest_time": "now",
"cancelOnUnload": true,
"status_buckets": 0,
"sample_ratio": 1,
"earliest_time": "-24h@h",
"app": utils.getCurrentApp(),
"auto_cancel": 90,
"preview": true,
"tokenDependencies": {
},
"runWhenTimeIsUndefined": false
}, {tokens: true, tokenNamespace: "submitted"});
new SearchEventHandler({
managerid: "search1",
event: "done",
conditions: [
{
attr: "any",
value: "*",
actions: [
{"type": "set", "token": "tokErrorCount", "value": "$result.Errors$"}
]
}
]
});
//
// SPLUNK LAYOUT
//
$('header').remove();
new LayoutView({"hideSplunkBar": false, "hideFooter": false, "hideChrome": false, "hideAppBar": false})
.render()
.getContainerElement()
.appendChild($('.dashboard-body')[0]);
//
// DASHBOARD EDITOR
//
new Dashboard({
id: 'dashboard',
el: $('.dashboard-body'),
showTitle: true,
editable: true
}, {tokens: true}).render();
//
// VIEWS: VISUALIZATION ELEMENTS
//
var element1 = new TableElement({
"id": "element1",
"count": 20,
"dataOverlayMode": "none",
"drilldown": "none",
"percentagesRow": "false",
"rowNumbers": "true",
"totalsRow": "false",
"wrap": "true",
"managerid": "search1",
"el": $('#element1')
}, {tokens: true, tokenNamespace: "submitted"}).render();
// Initialize time tokens to default
if (!defaultTokenModel.has('earliest') && !defaultTokenModel.has('latest')) {
defaultTokenModel.set({ earliest: '0', latest: '' });
}
submitTokens();
// Access the "default" token model
var defaultTokenModel = mvc.Components.get("default");
defaultTokenModel.on("change:tokErrorCount", function(newTokenName, tokErrorCount, options) {
if(tokErrorCount!==undefined && tokErrorCount!=="$result.Errors$"){
console.log("tokErrorCount: ",tokErrorCount);
}
});
//
// DASHBOARD READY
//
DashboardController.ready();
pageLoading = false;
}
);
// ]]>
</script>
</body>
</html>
Hi, yes I am using HTML with jQuery (splunk version 6.4). My HTML is similar to the one that you posted above.
Not sure if the query is running correctly. Is there any way to ensure the value of the token?
About the java script file, I need to retrieve the token value to display the value in a element that I have created using jquery/bootstrap...
How can I get it?
var status_execucao = document.getElementById('status_execucao');
Not working...
Hello Niketnilay,
Just noted that when I use "defaultTokenModel = mvc.Components.getInstance('submitted')", I got the error in the next line "defaultTokenModel.on("change:status_execucao", function(newTokenName, status_execucao, options)" because the variable defaultTokenModel is not yet setted.
And when I use "defaultTokenModel = mvc.Components.getInstance('default')", i am not facing the issue however the tokens are not yet setted, so i am not able to retrieve the values.
Probably it is happening because there is not enough time to load this code while the search is not yet finished.
How I can do to load continue the execution of the code only when the search is finished?
Thanks and regards,
Danillo Pavan
Hello Niketnilay, any help? Thanks!!
Hi @danilliopavan, sorry I missed seeing your questions... If you are on Splunk 6.4
you will not have done
or progress
event handler, instead you will have preview
and finalized
event handlers. i.e. instead of event: "done",
you should have the following:
event: "finalized",
Refer to Search Event Handler documentation in Splunk Docs for 6.4.7: https://docs.splunk.com/Documentation/Splunk/6.4.7/Viz/EventHandlerReference#preview
Also refer to following answer where we had to do several trials and errors to get the working HTML dashboard code from Simple XML: https://answers.splunk.com/answers/614832/how-to-add-icon-to-a-panel-instead-of-table-so-the.html