Getting Data In

How to create two text boxes on a dashboard with a submit button using JavaScript where entered values get stored in a CSV file?

abhayneilam
Contributor

Hi,

I want to create a dashboard in which two text boxes will be there with one submit button. Upon clicking the submit button, the values of those two boxes should be stored in a CSV file.

Please help me with this !!

Cheers

nick405060
Motivator

I did it without using JavaScript. The XML is relatively self-explanatory, two text boxes to fill out and a submit button. The query creates a table with the two fields entered in the text boxes, then outer joins it with the already existing csv, and then rewrites the csv with the join results. The last line in the query is just so it can be displayed as "Added:"

<form>
  <label>ABCMachines</label>

  <!-- Machine and tag text boxes, and add button, and display table of new adds-->
  <fieldset submitButton="true" autoRun="true">
    <input type="text" token="name">
      <label>Add machine name and new tag</label>
    </input>
    <input type="text" token="splunkTags">
      <label>
      </label>
    </input>
  </fieldset>
  <row>
    <panel>
      <title>Added:</title>
      <table>
        <search>
          <!-- Creates table of tag additions, appends the loaded master tag csv, dedups to result in either adding the data to the master
               or overwrite the existing data, and re-exports csv. Last line displays table -->
          <query>
 | stats count | eval Name="$name$" | eval Splunk_Tags="$splunkTags$" | table Name Splunk_Tags | append
[| inputcsv "splunk_tags.csv"] | dedup Name |
   outputcsv [| stats count | eval filename="splunk_tags.csv" | return $filename] |
   stats count | eval Name="$name$" | eval Splunk_Tags="$splunkTags$" | table Name Splunk_Tags
          </query>
        </search>
        <option name="wrap">true</option>
        <option name="rowNumbers">false</option>
        <option name="drilldown">cell</option>
        <option name="dataOverlayMode">none</option>
        <option name="count">10</option>
      </table>
    </panel>
  </row>

poete
Builder

Hello @abhayneilam, @pallavibalasa, @nick405060

you may want to download the splidget app (https://splunkbase.splunk.com/app/3649/)

The splunkpad in there is a very good example of writting in a dashboard the content of the user input and store it in a lookup file.

You will also need the lookup editor app if you do not already have it. (https://splunkbase.splunk.com/app/1724/)

0 Karma

kdimaria
Communicator

Please try the below HTML. I used outputcsv to create a csv file at first then it will continue to append to it once you hit submit. You can find the actual csv file in /opt/splunk/var/run/splunk/csv/
I display the results of the CSV file created using |inputcsv (I called it newcsv but you can change that)
I used JavaScript to grab the two values of the input boxes after hitting Submit then have a search that runs in the background to create and append to the csv file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Javascript into cvs</title>
    <link rel="shortcut icon" href="/en-US/static/@24D34014EFF4EDD633D5FCC87B2373BECCE2DBCDB974E848545A9EF99E0D05BF/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" />
    <link rel="stylesheet" type="text/css" media="all" href="{{SPLUNKWEB_URL_PREFIX}}/static/app/search/dashboard.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>Javascript into cvs</h2>
    </div>
    <div class="fieldset">
        input1: <input type="text" id="input1" size="20" name="input1">
        input2: <input type="text" id="input2" size="20" name="input2">
        <div class="form-submit" id="search_btn">
            <button class="btn btn-primary submit">Submit</button>
        </div>
    </div>
    <div class="dashboard-row">
    <div class="dashboard-cell" style="width: 25%">
        <div class="dashboard-panel" style="border-style:solid;border-color:#CCCCCC;border-width:1px;background:white;margin-right:2px;margin-left:2px;">
            <div style="margin-left:12px;margin-bottom:0px;">
                <h3 style="margin-bottom:0px;" title="This table captures key application per data center."><strong>newcsv.csv Data</strong></h3>
                </div>
                <div id="csvElement" class="dashboard-element table" style="width: 100%">
            </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 addToCSV = new SearchManager({
            id: "addToCSV",
            earliest_time: "0",
            latest_time: "now",
            preview: true,
            cache: false,
            search: "",
            }, {tokens: true, tokenNamespace: "submitted"});    

        var csvSearch = new SearchManager({
            id: "csvSearch",
            earliest_time: "0",
            latest_time: "now",
            preview: true,
            cache: false,
            search: "| inputcsv newcsv.csv",
            }, {tokens: true, tokenNamespace: "submitted"});

        //
        // SPLUNK LAYOUT
        //

        $('header').remove();
        new LayoutView({"hideChrome": false, "hideAppBar": false, "hideSplunkBar": 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 csvElement = new TableElement({
            "id": "csvElement",
            "count": 20,
            "dataOverlayMode": "none",
            "drilldown": "row",
            "rowNumbers": "false",
            "wrap": "true",
            "link.visible": true,
            "managerid": "csvSearch",
            "el": $('#csvElement')
        }, {tokens: true, tokenNamespace: "submitted"}).render();

        //
        // VIEWS: FORM INPUTS
        //



        // 
        // SUBMIT FORM DATA
        //

        var submit = new SubmitButton({
            id: 'submit',
            el: $('#search_btn')
        }, {tokens: true}).render();

        submit.on("submit", function() {
            var input1 = document.getElementById("input1").value;
            var input2 = document.getElementById("input2").value;
            addToCSV.settings.attributes.search = "| makeresults | eval input1=\"" + input1 + "\" | eval input2=\"" + input2 + "\" | outputcsv append=true newcsv";
            addToCSV.startSearch();
            alert("newcsv.csv has been created or added to. It is stored in /opt/splunk/var/run/splunk/csv/newcsv.csv");
            setTimeout(function(){csvSearch.startSearch();},2000);
        });

        // 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>
0 Karma

nick405060
Motivator

I'd like to do the exact same thing

nick405060
Motivator

Done! See my answer below

0 Karma

kdimaria
Communicator

Please see my answer I just posted.

0 Karma

pallavibalasa
Explorer

Hi ,
I am looking for a solution for a similar scenario. Please let me know if you are able to get the resolution for this.

Regards,
Pallavi

0 Karma

sundareshr
Legend

@pallavibalasa see if you can use this spur ideas.

http://dev.splunk.com/view/webframework-tutorials/SP-CAAAEZT

0 Karma

gwiley_splunk
Splunk Employee
Splunk Employee
0 Karma

abhayneilam
Contributor

Thanks Greg for your prompt reply !!

But my question is : I want to create an CSV file with the values I will put in the text box and click on add button.

So, first I will write my name in the text box and my age in another box then click on ADD button , then my name and age should be written in a CSV file.

Again if i give another value it should be appened in the existing value of my CSV file.

Cheers,

0 Karma
Get Updates on the Splunk Community!

Enterprise Security Content Update (ESCU) | New Releases

In December, the Splunk Threat Research Team had 1 release of new security content via the Enterprise Security ...

Why am I not seeing the finding in Splunk Enterprise Security Analyst Queue?

(This is the first of a series of 2 blogs). Splunk Enterprise Security is a fantastic tool that offers robust ...

Index This | What are the 12 Days of Splunk-mas?

December 2024 Edition Hayyy Splunk Education Enthusiasts and the Eternally Curious!  We’re back with another ...