Hi guys, I've been having this problem for a while now. I have a script that generates a hash for a file based on the file that was uploaded, and it then puts that hash into the input field. If you inspect the element on the page I can see the value has changed to the hash. But in order to make it search, I need to type in the field.
Any ideas?
Thanks.
Update: Working code, thanks to @niketnilay!
DashboardController.ready();
pageLoading = false;
$(document).ready(function () {
console.log("Step 1. Inside Document ready function");
$(document).on("click","#btn",function () {
console.log("Step 2. Button Clicked");
var reader = new FileReader(); //define a Reader
var file = $("#f1")[0].files[0]; //get the File object
if (!file) {
alert("no file selected");
return;
} //check if user selected a file
reader.onload = function (f) {
console.log("Step 3. Reader on load function");
var file_result = this.result; // this == reader, get the loaded file "result"
var file_wordArr = CryptoJS.lib.WordArray.create(file_result); //convert blob to WordArray , see https://code.google.com/p/crypto-js/issues/detail?id=67
var sha1_hash = CryptoJS.SHA1(file_wordArr); //calculate SHA1 hash
//alert("Calculated SHA1:" + sha1_hash.toString()); //output result
$('#input1_3519-input').attr('value', sha1_hash);
setTimeout(function(){
console.log("Step 4 updated token values");
defaultTokenModel.set("form.search_hash_url", sha1_hash);
defaultTokenModel.set("search_hash_url", sha1_hash);
},10);
};
reader.readAsArrayBuffer(file); //read file as ArrayBuffer
});
});
}
);
// ]]>
@JarrenJ, would it be possible for you to add the code for event which is used to set the textbox value?
If there are no events then you can use setTimeout() JavaScript function to set both form.search_hash_url
(which should update the value in Splunk Text Box input) and search_hash_url
(which should set the token used in dashboard for running search).
As you can see there is no need to depend on jQuery to use attr()
function to set the value for Splunk Text Box Input. I was under impression that you are using HTML text box.
Also, if you are using HTML dashboard and not Simple XML JS Extension on top of Simple XML Dashboard, you should search the code as HTML dashboard by default get both defaultTokenModel
and submittedTokenModel
. Which implies you do not have to explicitly call var defaultTokenModel=mvc.Components.get("default");
. Please try out the following code and confirm:
setTimeout(function(){
//Set the Splunk Text Input value using token form.search_hash_url
defaultTokenModel.set("form.search_hash_url","testing");
//Set the token for Splunk Dashboard search using token search_hash_url
defaultTokenModel.set("search_hash_url","testing");
},10);
Following should work as well based on what you are trying, however, above approach with form.search_hash_url
and search_hash_url
is better since you are using Splunk Text Input not HTML.
setTimeout(function(){
// Set the value for Splunk Text Input using jQuery attr() function
$("div#input1 div.splunk-textinput input").attr("value", "testing");
//Set the token for Splunk Dashboard search using token search_hash_url
defaultTokenModel.set("search_hash_url","testing");
},10);
I have used setTimeout()
JavaScript function for example. You should code this inside that change event for file hash name, when it gets populated.
@JarrenJ, would it be possible for you to add the code for event which is used to set the textbox value?
If there are no events then you can use setTimeout() JavaScript function to set both form.search_hash_url
(which should update the value in Splunk Text Box input) and search_hash_url
(which should set the token used in dashboard for running search).
As you can see there is no need to depend on jQuery to use attr()
function to set the value for Splunk Text Box Input. I was under impression that you are using HTML text box.
Also, if you are using HTML dashboard and not Simple XML JS Extension on top of Simple XML Dashboard, you should search the code as HTML dashboard by default get both defaultTokenModel
and submittedTokenModel
. Which implies you do not have to explicitly call var defaultTokenModel=mvc.Components.get("default");
. Please try out the following code and confirm:
setTimeout(function(){
//Set the Splunk Text Input value using token form.search_hash_url
defaultTokenModel.set("form.search_hash_url","testing");
//Set the token for Splunk Dashboard search using token search_hash_url
defaultTokenModel.set("search_hash_url","testing");
},10);
Following should work as well based on what you are trying, however, above approach with form.search_hash_url
and search_hash_url
is better since you are using Splunk Text Input not HTML.
setTimeout(function(){
// Set the value for Splunk Text Input using jQuery attr() function
$("div#input1 div.splunk-textinput input").attr("value", "testing");
//Set the token for Splunk Dashboard search using token search_hash_url
defaultTokenModel.set("search_hash_url","testing");
},10);
I have used setTimeout()
JavaScript function for example. You should code this inside that change event for file hash name, when it gets populated.
@niketnilay, I can get the code to work if i put the setTimeout Function in the dashboard.ready section of my code. My problem is that I need to set it when I click a certain button, but when i try to change the tokens in my script from above, it doesn't do anything. Any ideas or suggestions? If not its ok, you have been a big help.
@JarrenJ, if setTimeout()
works on document.ready()
can you try the same inside the following button click event $("#btn").click(function ()
? Ideally if Button Click is working then setTimeout
inside button click should also work.
Let me know if it works and I can convert the comment to answer for you to Accept the same. Also up vote the comments that helped as this has been a long thread now 🙂
All the best!
@niketnilay, Updated code, in response to latest comment below...
<script>
$(document).ready(function () {
console.log("Step 1. Inside Document ready function");
$("#btn").click(function () {
console.log("Step 2. Button Clicked");
var reader = new FileReader(); //define a Reader
var file = $("#f1")[0].files[0]; //get the File object
if (!file) {
alert("no file selected");
return;
} //check if user selected a file
reader.onload = function (f) {
console.log("Step 3. Reader on load function");
var file_result = this.result; // this == reader, get the loaded file "result"
var file_wordArr = CryptoJS.lib.WordArray.create(file_result); //convert blob to WordArray , see https://code.google.com/p/crypto-js/issues/detail?id=67
var sha1_hash = CryptoJS.SHA1(file_wordArr); //calculate SHA1 hash
//alert("Calculated SHA1:" + sha1_hash.toString()); //output result
$('#input1_3519-input').attr('value', sha1_hash);
setTimeout(function(){
console.log("Step 4 updated token values");
defaultTokenModel.set("form.search_hash_url", "testing");
defaultTokenModel.set("search_hash_url", "testing");
},10);
};
reader.readAsArrayBuffer(file); //read file as ArrayBuffer
});
});
</script>
I meant this:
<script>
$(document).ready(function () {
//console.log("Step 1. Inside Document ready function);
$("#btn").click(function () {
setTimeout(function(){
//console.log("Step 2. Button Clicked";)
var reader = new FileReader(); //define a Reader
var file = $("#f1")[0].files[0]; //get the File object
if (!file) {
alert("no file selected");
return;
} //check if user selected a file
reader.onload = function (f) {
//console.log("Step 3. Reader on load function");
var file_result = this.result; // this == reader, get the loaded file "result"
var file_wordArr = CryptoJS.lib.WordArray.create(file_result); //convert blob to WordArray , see https://code.google.com/p/crypto-js/issues/detail?id=67
var sha1_hash = CryptoJS.SHA1(file_wordArr); //calculate SHA1 hash
//alert("Calculated SHA1:" + sha1_hash.toString()); //output result
//$('#input1_3519-input').attr('value', sha1_hash);
//defaultTokenModel.set("form.search_hash_url","testing");
//defaultTokenModel.set("search_hash_url","testing");
//$("div#input1 div.splunk-textinput input").attr("value", "testing");
defaultTokenModel.set("form.search_hash_url","testing");
defaultTokenModel.set("search_hash_url","testing");
};
},10);
reader.readAsArrayBuffer(file); //read file as ArrayBuffer
});
});
</script>
Give one more thing a try
$(document).on("click","#btn",function () {
Instead of $("#btn").click(function () {
Refer to the following answer by @Jeffland: https://answers.splunk.com/answers/587821/assistance-with-javascript-code-to-accommodate-an.html
@Niketnilay, The code you suggested, makes a new error. reader is not defined. Even though it is in the SetTimeout Function.
Ok then keep the previous code and try changing $("#btn").click(function () {
to
$(document).on("click","#btn",function () {
However, I am also drawing blanks here. So, if this does not work then keep the setTimeout()
inside document.ready()
which worked for your.
Do up vote any comments that helped. I will still leave the question as unanswered!
@niketnilay, YES! The code worked. I just needed to put in in the dashboard.ready function at he bottom of the page. See new working code below!
DashboardController.ready();
pageLoading = false;
$(document).ready(function () {
console.log("Step 1. Inside Document ready function");
$(document).on("click","#btn",function () {
console.log("Step 2. Button Clicked");
var reader = new FileReader(); //define a Reader
var file = $("#f1")[0].files[0]; //get the File object
if (!file) {
alert("no file selected");
return;
} //check if user selected a file
reader.onload = function (f) {
console.log("Step 3. Reader on load function");
var file_result = this.result; // this == reader, get the loaded file "result"
var file_wordArr = CryptoJS.lib.WordArray.create(file_result); //convert blob to WordArray , see https://code.google.com/p/crypto-js/issues/detail?id=67
var sha1_hash = CryptoJS.SHA1(file_wordArr); //calculate SHA1 hash
//alert("Calculated SHA1:" + sha1_hash.toString()); //output result
$('#input1_3519-input').attr('value', sha1_hash);
setTimeout(function(){
console.log("Step 4 updated token values");
defaultTokenModel.set("form.search_hash_url", sha1_hash);
defaultTokenModel.set("search_hash_url", sha1_hash);
},10);
};
reader.readAsArrayBuffer(file); //read file as ArrayBuffer
});
});
}
);
// ]]>
Thank you so much for all your help, you have me helped me so much!
Great news @JarrenJ. I have converted my comment as Answer. Accept to mark this question as answered. I see you have already up voted the comments that helped 🙂
@niketnilay, I figured out why adding in console.log broke it, i forgot a quote which made everything after it a string... I fixed it, and all 3 of my console logs fire off correctly, without the SetTimeout Function included. With the SetTimeout function added an extra console.log, it hits the SetTimout function but errors out and tells me that defaultTokenModel is not defined.
@niketnilay, sorry for the late response, I only work on this project while at my internship (2 hours a day, Tuesday - Friday). I edited my question with the full code, let me know if that's what you were looking for.
@JarrenJ, where you have the following code: $('#input1_3520-input').attr('value', sha1_hash);
. Replace it with the following:
//Set the Splunk Text Input value using token form.search_hash_url
defaultTokenModel.set("form.search_hash_url","testing");
//Set the token for Splunk Dashboard search using token search_hash_url
defaultTokenModel.set("search_hash_url","testing");
Try out when the time permits and confirm. Hope the difference between regular token and form token is clear. You can get Splunk on your personal machine for testing. You should also get Splunk Dashboard Examples app from Splunkbase.
Following is a run anywhere HTML Dashboard based on my answer above (created in Splunk Enterprise 7.0). It uses setTimeout()
but that is only for understanding.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Set token for Search query on setting the text box HTML</title>
<link rel="shortcut icon" href="/en-US/static/@6DBB1CA03DD228D3B100891FF1ABA8E0B78408B35943159C8CB0A6A6CD8F2A21.1/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>
(function () {
window._splunk_metrics_events = [];
window._splunk_metrics_events.active = true;
function onLoadSwa() {
new SWA({"url": "https://e1345286.api.splkmobile.com/1.0/e1345286", "version": "3", "deploymentID": "5f8fa96b-386e-5a03-8152-928eacfd52b7", "visibility": "anonymous,support", "userID": "8333414143d88d4f6a6f3e242cfda02f0dd9fcc451683eaa46f43b9a524e4250", "instanceGUID": "650A6948-AA26-4607-B76B-2CE352FB32B7"});
};
document.addEventListener("DOMContentLoaded", function(event) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = '/en-US/static/app/splunk_instrumentation/build/pages/swa.js';
s.addEventListener('load', onLoadSwa);
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
});
}());
</script>
</head>
<body class="simplexml preload locale-en" data-splunk-version="7.0.2" 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>Splunk Answers 636564 - Set token for Search query on setting the text box HTML</h2>
</div>
<div class="fieldset">
<div class="input input-text" id="input1">
<label>SHA1 HASH VAlue</label>
</div>
</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",
"cancelOnUnload": true,
"latest_time": "$latest$",
"sample_ratio": null,
"earliest_time": "$earliest$",
"status_buckets": 0,
"search": "| makeresults | fields - _time | eval value=\"$search_hash_url$\"",
"app": utils.getCurrentApp(),
"auto_cancel": 90,
"preview": true,
"tokenDependencies": {
},
"runWhenTimeIsUndefined": false
}, {tokens: true, tokenNamespace: "submitted"});
//
// SPLUNK LAYOUT
//
$('header').remove();
new LayoutView({"hideSplunkBar": false, "hideAppBar": false, "hideChrome": false, "hideFooter": 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",
"managerid": "search1",
"el": $('#element1')
}, {tokens: true, tokenNamespace: "submitted"}).render();
//
// VIEWS: FORM INPUTS
//
var input1 = new TextInput({
"id": "input1",
"searchWhenChanged": true,
"value": "$form.search_hash_url$",
"el": $('#input1')
}, {tokens: true}).render();
input1.on("change", function(newValue) {
FormUtils.handleValueChange(input1);
});
DashboardController.onReady(function() {
if (!submittedTokenModel.has('earliest') && !submittedTokenModel.has('latest')) {
submittedTokenModel.set({ earliest: '0', latest: '' });
}
});
// 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;
setTimeout(function(){
//$("div#input1 div.splunk-textinput input").attr("value", "testing");
defaultTokenModel.set("form.search_hash_url","testing");
defaultTokenModel.set("search_hash_url","testing");
},10);
}
);
// ]]>
</script>
</body>
</html>
@niketnilay, as seen in EDIT 3 of my question, I added the code you gave me and it didn't work. It doesn't populate the text field or let me run a search.
Can you also add console.log to debug? and add submitedtTokenModel as well (although I feel this is not required)?
Did you get to try the run anywhere example which I have provided above?
$(document).ready(function () {
console.log("Step1. Inside Document Ready Function");
$("#btn").click(function () {
console.log("Step2. Button Clicked");
var reader = new FileReader(); //define a Reader
var file = $("#f1")[0].files[0]; //get the File object
if (!file) {
alert("no file selected");
return;
} //check if user selected a file
reader.onload = function (f) {
console.log("Step3. Reader On Load Function");
var file_result = this.result; // this == reader, get the loaded file "result"
var file_wordArr = CryptoJS.lib.WordArray.create(file_result); //convert blob to WordArray , see https://code.google.com/p/crypto-js/issues/detail?id=67
var sha1_hash = CryptoJS.SHA1(file_wordArr); //calculate SHA1 hash
//alert("Calculated SHA1:" + sha1_hash.toString()); //output result
//$('#input1_3520-input').attr('value', sha1_hash);
//Set the Splunk Text Input value using token form.search_hash_url
defaultTokenModel.set("form.search_hash_url", "testing");
submittedTokenModel.set("form.search_hash_url", "testing");
//Set the token for Splunk Dashboard search using token search_hash_url
defaultTokenModel.set("search_hash_url", "testing");
submittedTokenModel.set("search_hash_url", "testing");
};
reader.readAsArrayBuffer(file); //read file as ArrayBuffer
});
});
Can you give what your text input input1
code looks like? It should be similar to the one below ie. "value": "$form.search_hash_url$",
? Also, the change event handler for input1 should be defined.
var input1 = new TextInput({
"id": "input1",
"searchWhenChanged": true,
"value": "$form.search_hash_url$",
"el": $('#input1')
}, {tokens: true}).render();
input1.on("change", function(newValue) {
FormUtils.handleValueChange(input1);
});
@niketnilay, when I add the console logs, it breaks my script for some reason. Without them it also doesn't work. Here is my input1 code...
var input1 = new TextInput({
"id": "input1",
"searchWhenChanged": true,
"suffix": "",
"default": "$url:UrlHash$",
"value": "$form.search_hash_url$",
"el": $('#input1')
}, {tokens: true}).render();
input1.on("change", function(newValue) {
FormUtils.handleValueChange(input1);
});
@niketnilay, I made a new dashboard and copied your run anywhere code from above into it and it worked perfectly. How would I implement that into my current code?
@JarrenJ HTML dashboards are tricky and complicated. Without information of your code and console logs it will be tough to figure out whats not working with your Javascript. I don't see any reason why console.log() would error out/not work if rest of your script without them works fine. Is there any console error (maybe syntax), which shows up in developer mode?
Would you be able to take the assistance from someone working on the project who can figure out issue with JavaScript ? Even better if they know Splunk Web Framework/Splunk JS Stack?
I am not sure whether I can provide further assistance beyond run any where dashboard example, considering the fact that I do not have access to your Splunk instance with data/code. Hope you would be able to figure out the issue. Meanwhile I will convert my answer to comment so that it shows up as unanswered for other Splunkers to assist.
Guessing that this is a dashboard, have you tried setting the token form.tokenName
, tokenName being the name of the token behind the input? That should set the input.
its a dashboard but converted to HTML. I set the value using jquery, by selecting the ID of the input and changing the attribute VALUE to the generated hash, it puts it in the search box, but it doesn't search unless i manually type something in it.
@JarrenJ, when you update the Text Box content using jQuery, you can also update the textbox token value and textbox form token value using set
, provided, token for textbox is used in the search:
Refer to the following URL: http://dev.splunk.com/view/webframework-developapps/SP-CAAAEW3
If you are sure that token is being set and should be picked up by the query, you can also run <yourSearchManagerID>.startSearch()
command to force the search to run.
If none of the above work, you might have to share your existing code. Mock/Anonymize any sensitive information before posting.