Date post: | 07-Jul-2015 |
Category: |
Technology |
Upload: | nagios |
View: | 788 times |
Download: | 4 times |
JavaScript and jQueryNagios XI Tips, Tricks
and How-To
Troy Lea aka Box293
Twitter: @box293
Introduction & Agenda
• JavaScript and jQuery … it's the #1 cause of baldness!
• This presentation explains JavaScript and jQuery
What is JavaScript?
• It allows you to change the content of the end users web page• Called the “client side”
• Can be performed as an action based on a users selection or particular mouse click
• No need to reload the entire page
What is JavaScript?
• It's FRUSTRATING !!!
https://coderwall.com/p/y8gjbq
What is jQuery?
• A library of functions that make using JavaScript easier
• jQuery is whatJavaScript shouldhave been
Time for some code
• We'll start with some basic examples and expand from there
• WARNING:
<CODE>
ahead
CODE Notes
• Files need to be:
• Mode = Unix (LF)
• Encoding = UTF-8
• This will prevent headaches
JavaScript Alert – Part 1
index.html
<!doctype html><html><head> <meta charset="utf8" /> <title>Demo</title></head><body> Blah blah blah <br/><br/> <input type="button" value="Click Me" onclick="say_hello()">
<script> function say_hello() { alert('say hello'); } </script></body></html>
onclick="say_hello()"
function say_hello() {alert('say hello');}
onclick="say_hello()"
function say_hello() {alert('say hello');}
JavaScript Alert – Part 2
index.html
<!doctype html> <html> <head> <meta charset="utf8" /> <title>Demo</title> </head> <body> Blah blah blah <br/><br/> <input type="button" value="Click Me" onclick="say_hello('GDay Mate')"> <script> function say_hello(input) { alert(input); } </script> </body> </html>
onclick="say_hello('GDay Mate')"
function say_hello(input) { alert(input); }
onclick="say_hello('GDay Mate')"
function say_hello(input) { alert(input); }
JavaScript Alert – Part 3
Example 1 = Called a function without any values
onclick="say_hello()"
function say_hello() {alert('say hello');}
Example 2 = Called a function sending a value
onclick="say_hello('GDay Mate')"
function say_hello(input) { alert(input); }
Quick Break
<SELECT> – JavaScript
JavaScript
Blah blah blah<br/><br/><select id="id_select">
<option value="Value A">Value A</option><option value="Option 2">Option 2</option>
</select><br/><br/><input type="button" value="Click Me" onclick="select_value('id_select')">
<script>function select_value(input) {
var the_element = document.getElementById(input);var the_value = the_element.options[the_element.selectedIndex].value;alert(the_value);}
</script>
var the_element = document.getElementById(input);
var the_value = the_element.options[the_element.selectedIndex].value;
alert(the_value);
var the_element = document.getElementById(input);
var the_value = the_element.options[the_element.selectedIndex].value;
alert(the_value);
<SELECT> – jQuery
jQuery
Blah blah blah <br/><br/> <select id="id_select">
<option value="Value A">Value A</option><option value="Option 2">Option 2</option>
</select> <br/><br/> <input type="button" value="Click Me" onclick="select_value('id_select')">
<script src="jquery2.1.1.min.js"></script> <script>function select_value(input) {
var the_value = $('#' + input).val(); alert(the_value); }
</script>
<script src="jquery2.1.1.min.js"></script> <script>function select_value(input) {
var the_value = $('#' + input).val();
alert(the_value); }
</script>
<script src="jquery2.1.1.min.js"></script> <script>function select_value(input) {
var the_value = $('#' + input).val();
alert(the_value); }
</script>
<SELECT> – Summary
Common HTML<input type="button" value="Click Me" onclick="select_value('id_select')">
JavaScript<script>function select_value(input) {
var the_element = document.getElementById(input);var the_value = the_element.options[the_element.selectedIndex].value;alert(the_value);}
</script>
jQuery<script src="jquery2.1.1.min.js"></script> <script>function select_value(input) {
var the_value = $('#' + input).val(); alert(the_value); }
</script>
Quick Break
Separate JavaScript File – Part 1
index.html
<!doctype html> <html> <head> <meta charset="utf8" /> <title>Demo</title> </head> <body> Blah blah blah <br/><br/> <select id="id_select"> <option value="Value A">Value A</option> <option value="Option 2">Option 2</option> </select> <br/><br/> <input type="button" value="Click Me" onclick="select_value('id_select')"> <script src="jquery2.1.1.min.js"></script> <script src="my_javascript.js"></script> </body> </html>
Separate JavaScript File – Part 2
my_javascript.js
function select_value(input) { var the_value = $('#' + input).val(); alert(the_value); }
● Separating the JavaScript/jQuery from the HTML file
● Makes coding easier● Code works the same
Quick Break
PHP – Time To Get Complicated
● PHP = "PHP: Hypertext Preprocessor"
– It's a recursive backronym!● Builds HTML code on the fly● PHP code is between the tags
– <?php– ?>
PHP – Javascript Alertindex.php
<?php $output = '
<!doctype html> <html> <head>
<meta charset="utf8" /> <title>Demo</title>
</head> <body> Blah blah blah <br/><br/> <input type="button" value="Click Me" onclick="say_hello()">
<script>function say_hello() {
alert(\'say hello\'); }
</script> </body> </html>
'; print $output; ?>
onclick="say_hello()"
function say_hello() {alert(\'say
hello\');}
onclick="say_hello()"
function say_hello() {alert(\'say
hello\');}
PHP – Escaping Quotes Part 1
● PHP Variables use quotes for the variable value
– Single ' OR Double “
$test = 'Hello There and some HTML Code <br />';
OR
$test = "Hello There and some HTML Code <br />";
PHP – Escaping Quotes Part 2
● Without escaping, PHP thinks the variable is finished and does not expect the characters that follow
$test = 'Hey look it\'s a single quote <br />';
OR
$test = "He said \"GDay Mate\" <br />";
PHP – Escaping Quotes Part 3index.php
<?php$output = '
<!doctype html> <html> <head>
<meta charset="utf8" /> <title>Demo</title>
</head> <body>
Blah blah blah <br/><br/> <select id="id_select"> <option value="Value A">Value A</option> <option value="Option 2">Option 2</option> </select> <br/><br/> <input type="button" value="Click Me" onclick="select_value(\'id_select\')"> <script src="jquery2.1.1.min.js"></script> <script src="my_javascript.js"></script>
</body> </html>
';print $output;?>
onclick="select_value(\'id_select\')"
onclick="select_value(\'id_select\')"
PHP – Escaping Quotes Part 4
my_javascript.js
function select_value(input) { var the_value = $('#' + input).val(); alert(the_value); }
● In the separate JavaScript file no escaping is required
● On the previous slide we needed to escape the single quotes:
● onclick="select_value(\'id_select\')"
PHP – Escaping Quotes Part 5
● Double quotes = PHP variables are expanded, which allows the content to change dynamically
$food_item = "pizza"; $output = "My favorite food is $food_item";
● $output will now contain:
My favorite food is pizza
PHP – Escaping Quotes Part 6
● Single quotes = The content between the single quotes is treated as plain text (literal)
$food_item = 'pizza'; $output = 'My favorite food is $food_item';
● $output will now contain:
My favorite food is $food_item
$food_item was not not expanded, it was treated as plain text
PHP – Escaping Quotes Part 7
● So then why don't I use double quotes like: ●$output = "HTML content";
● Then we won't have to escape those single quotes right?
● Lets see …
PHP – Escaping Quotes Part 8index.php
<?php$output = " <!doctype html> <html> <head> <meta charset=\"utf8\" /> <title>Demo</title> </head> <body>
Blah blah blah <br/><br/> <input type=\"button\" value=\"Click Me\" onclick=\"say_hello()\"> <script> function say_hello() { alert('say hello'); } </script> </body> </html> ";
print $output;?>
PHP – Escaping Quotes Part 9
● So now you can see that while I didn't need to escape two single quotes, I needed to escape eight double quotes!
● It's not right or wrong … there's just different ways to do the same thing
Quick Break
Hiding and Showing – Part 1HTML
<body> Blah blah blah<br/><br/> <select id="id_select">
<option value="one">Strawberry</option> <option value="two">Grape</option>
</select> <br/><br/> <input type="button" value="Click Me" onclick="show_item(\'id_select\')"><br/><br/>
<div id="id_one" class="foods" style="display:none;"> <img src="foodstrawberry.png">
</div>
<div id="id_two" class="foods" style="display:none;"> <img src="foodgrapes.png">
</div>
<script src="jquery2.1.1.min.js"></script> <script src="my_javascript.js"></script>
</body>
<div id="id_one" class="foods" style="display:none;">
<img src="foodstrawberry.png"> </div>
<div id="id_two" class="foods" style="display:none;">
<img src="foodgrapes.png"> </div>
<div id="id_one" class="foods" style="display:none;">
<img src="foodstrawberry.png"> </div>
<div id="id_two" class="foods" style="display:none;">
<img src="foodgrapes.png"> </div>
Hiding and Showing – Part 2my_javascript.js
function show_item(input) { var item_selected = $('#' + input).val();$('.foods').hide(); $('#id_' + item_selected).show();}
First Load Strawberry Grape
function show_item(input) { var item_selected = $('#' +
input).val();$('.foods').hide(); $('#id_' + item_selected).show();}
function show_item(input) { var item_selected = $('#' +
input).val();$('.foods').hide(); $('#id_' + item_selected).show();}
Quick Break
What is AJAX?
• A group of technologies used to implement web applications
• Communication with a server in the background
• Does not interfere with the current state of the page
AJAX Example – Part 1index.php
<?php $output = ' <!doctype html>
<html><head>
<meta charset="utf8" /><title>Demo</title>
</head><body>
Blah blah blah<br/><br/><select id="id_select">
<option value="one">Strawberry</option><option value="two">Grape</option>
</select><br/><br/><input type="button" value="Click Me" onclick="load_content(\'id_select\')"><br/><br/>
<div id="id_content"><! this will be populated later >
</div>
<script src="jquery2.1.1.min.js"></script><script src="my_javascript.js"></script>
</body></html>';
print $output; ?>
<div id="id_content"><! this will be populated
later ></div>
<div id="id_content"><! this will be populated
later ></div>
AJAX Example – Part 2my_javascript.js
function load_content(input) {var item_selected = $('#' + input).val();var div_to_load = '#id_content';$(div_to_load).load('content.php?selection=' + item_selected);}
content.php
<?php $selection = $_GET['selection'];if ($selection == 'one') {
$output = '<img src="foodstrawberry.png">';}
elseif ($selection == 'two') {$output = '<img src="foodgrapes.png">';}
print $output; ?>
AJAX Example – Part 3
$(div_to_load).load('content.php?selection=' + item_selected);
● .load() is a jQuery function that performs the AJAX request
● Server is told to load the page content.php● “selection” is passed as a variable with the value
of item_selected● Only the required HTML is generated● .load() REPLACES the DIV contents
Examples - Conclusion
● These examples have demonstrated simple HTML and JavaScript/jQuery functionality along with AJAX
● Next I will demonstrate how to use these technologies in Nagios XI
Nagios XI
● Component Demo
● GOAL:● Show a list of hosts● Select a host, show a list of services for that
host● Demo code will be made available with the
presentation after the conference
Component Demo - Part 1
Extract from componentdemo.inc.php
case COMPONENT_CONFIGMODE_GETSETTINGSHTML:$output .= '
Hey there and welcome to the demo!<br/><br/><br/>
<div id="id_hosts"><! This will be populated by the line of script below →
</div>
<script>populate_hosts()</script>
<br/><br/><br/>
<div id="id_services"><! This will be populated by the users host selection →
</div>
<br/><br/><br/><br/><br/><br/><br/><br/><br/>Ignore these two buttons below, they are here by default and don\'t serve
any purpose in this demo.';
break; /* End case COMPONENT_CONFIGMODE_GETSETTINGSHTML: */
Component Demo - Part 2
componentdemo.js
function populate_hosts() {var div_to_load = '#id_hosts';$
(div_to_load).load('/nagiosxi/includes/components/componentdemo/componentdemo_misc.php?request=hosts');
}
function populate_services() {var div_to_load = '#id_services';var host_selected = $('#id_nagios_hosts').val(); $
(div_to_load).load('/nagiosxi/includes/components/componentdemo/componentdemo_misc.php?request=services&host_name=' + encodeURIComponent(host_selected));
}
Component Demo - Part 3
Extract from componentdemo_misc.php
case 'hosts':/* Get the hosts */$args = array(
'is_active' => 1,'orderby' => 'host_name:a',);
/* Returns an XML object, this is NOT an array. */$xmlhosts = get_xml_host_objects($args);
/* Now create a select of the hosts */$componentdemo_output .= '<select id="id_nagios_hosts">';foreach($xmlhosts>host as $h){
#print_r($h>host_name . " = " . $h>address . "<br/>");$componentdemo_output .= '<option value="'.$h>host_name.'">'.$h
>host_name.'</option>';} /* End foreach($xmlhosts>host as $h){ */
$componentdemo_output .= '</select>';
$componentdemo_output .= '<br/><br/><input type="button" value="Get Host\'s Services"
onclick="populate_services()"><br/>';
break; /* End case 'hosts': */
Component Demo - Part 4
componentdemo.js
function populate_hosts() {var div_to_load = '#id_hosts';$
(div_to_load).load('/nagiosxi/includes/components/componentdemo/componentdemo_misc.php?request=hosts');
}
function populate_services() {var div_to_load = '#id_services';var host_selected = $('#id_nagios_hosts').val(); $
(div_to_load).load('/nagiosxi/includes/components/componentdemo/componentdemo_misc.php?request=services&host_name=' + encodeURIComponent(host_selected));
}
Component Demo - Part 5
Extract from componentdemo_misc.php
case 'services':/* Get the host name passed to us */$host_name = urldecode(grab_request_var('host_name',false));
/* Service status fetch, brief listing, sorted by host_name */$args = array(
'cmd' => 'getservicestatus','has_been_checked' => 1,'host_name' => $host_name,'is_active' => 1,'brevity' => 3,);
/* Returns an XML object, this is NOT an array. */$statusinfo_services_xml = get_xml_service_status($args);
/* Make sure we've got results to display */if (count($statusinfo_services_xml>servicestatus) > 0) {
$componentdemo_output .= '<table><thead><tr><th style="textalign:left;">Service Name</th><th
style="width:10px;"></th><th style="width:40px;">State</th><th style="textalign:left;">Status</th></tr></thead>
';
DON'T use
$_GET['xxx']
INSTEAD use
grab_request_var('xxx',false)
Component Demo - Part 6
Extract from componentdemo_misc.php
foreach($statusinfo_services_xml>servicestatus as $service) {$service_name = "$service>name";$current_state = "$service>current_state";$status_text = "$service>status_text";
$componentdemo_output .= '<tr><td>'.$service_name.'</td><td> </td><td style="textalign:center;">'.$current_state.'</td><td>'.$status_text.'</td></tr>';
} /* End foreach($statusinfo_services_xml>servicestatus as $service) { */
$componentdemo_output .= '</table>';} /* End if (count($statusinfo_services_xml>servicestatus) > 0) { */
else {/* This host does not have any services */$componentdemo_output .= 'This host does not have any services!';} /* End else { */
break; /* End case 'services': */
Component Demo - Part 7
● You can see how to access the backend API to get Nagios objects
● Loading DIV's makes this easy and dynamic
Quick Break
(¯`·._.· Making It Pretty ·._.·´¯)
● Add a spinning logo that will be displayed when the AJAX calls are being made
● AJAX = Asynchronous = Complications● AJAX options will make this work consistently● The AJAX code will appear differently for the
hosts vs services. This demonstrates different methods of using the jQuery AJAX (required because of the encodeuri function)
Making It Pretty - Part 1
Extract from componentdemo.inc.php
<div id="id_hosts_throbber" style="display:none"><br />'.get_throbber_html().'
</div>
<div id="id_hosts"><! This will be populated by the line of script below >
</div>
<script>populate_hosts()</script>
<br/><br/><br/>
<div id="id_services_throbber" style="display:none"><br />'.get_throbber_html().'
</div>
<div id="id_services"><! This will be populated by the users host selection >
</div>
Making It Pretty - Part 2
Extract from componentdemo.js
// This makes an ajax call synchronousfunction componentdemo_ajaxSetup() {
$.ajaxSetup({async: false,cache: false,}); // End $.ajaxSetup({
} // End function componentdemo_ajaxSetup() {
function populate_hosts() {var div_to_load = '#id_hosts';var div_throbber_id = '#id_hosts_throbber';$(div_to_load).hide();$(div_throbber_id).show();componentdemo_ajaxSetup();$
(div_to_load).load('/nagiosxi/includes/components/componentdemo/componentdemo_misc.php?request=hosts',
function() {$(div_throbber_id).hide();$(div_to_load).show();} // End function() {
); // End $(div_to_load).load(} // End function populate_hosts() {
Making It Pretty - Part 3
● While a list of hosts are retrieved a spinning logo is shown
Making It Pretty - Part 4Extract from componentdemo.js
// This makes an ajax call synchronousfunction componentdemo_ajaxSetup() {
$.ajaxSetup({async: false,cache: false,}); // End $.ajaxSetup({
} // End function componentdemo_ajaxSetup() {
function populate_services() {var div_to_load = '#id_services';var host_selected = $('#id_nagios_hosts').val(); var div_throbber_id = '#id_services_throbber';$(div_to_load).hide();$(div_throbber_id).show();componentdemo_ajaxSetup();$
(div_to_load).load('/nagiosxi/includes/components/componentdemo/componentdemo_misc.php',{
'request' : 'services','host_name' : encodeURIComponent(host_selected)},
function() {$(div_throbber_id).hide();$(div_to_load).show();} // End function() {
); // End $(div_to_load).load(} // End function populate_services() {
Making It Pretty - Part 5
● While a list of services are retrieved a spinning logo is shown
Quick Break
Efficient Coding - Part 1
Example:
Status Info Dashlet
Efficient Coding - Part 2Extract from the “Status Info Dashlet” available on the Nagios Exchange
// Define a unique DIV$statusinfo_inboard_object_container_div = 'statusinfo_inboard_object_container_' .$id;
$output='<! This is the DIV that holds the inboard dashlet ><div id="'.$statusinfo_inboard_object_container_div.'">
'.get_throbber_html().'</div>
<! create an anonymous function to refresh the dashlet at the userdefined interval >
<script type="text/javascript"><! This makes the inboard dashlet content do the inital load >$("#'.
$statusinfo_inboard_object_container_div.'").load("/nagiosxi/includes/dashlets/statusinfo/statusinfo_inboard.php?statusinfo_inboard_args='.urlencode(base64_encode(serialize($args))).'");
<! This makes the inboard dashlet refresh at the userdefined interval >setInterval(function() {
$("#'.$statusinfo_inboard_object_container_div.'").load("/nagiosxi/includes/dashlets/statusinfo/statusinfo_inboard.php?statusinfo_inboard_args='.urlencode(base64_encode(serialize($args))).'");
},'.$statusinfo_inboard_refresh_interval.'); </script>';
Quick Break
Troubleshooting – Part 1
● The smallest error in your JavaScipt / jQuery code can cause everything to break
● Test frequently – don't code 300 lines in one chunk otherwise you may spend ages working out where your issue is
● alert() is a simple method for locating where the issue is occurring
● console.log() is a better debugging method
Troubleshooting – Part 2
● Alert example● alert('It\'s working and the value of #id_nagios_hosts is: \'' + host_selected + '\'');
● Tip: Surround values with quotes (helps identify when you have a blank value)
Troubleshooting – Part 3
● console.log() example● console.log('It\'s working and the value of #id_nagios_hosts is: \'' + host_selected + '\'');
● Depending on your browser, access the console logs with: F12 or CTRL + SHIFT + J
Troubleshooting – Part 4
● Comment out lines of code to disable them● This can help identify where the issue is without
having to remove the code entirely● It's two forward slashes //function populate_hosts() {
var div_to_load = '#id_hosts';var div_throbber_id = '#id_hosts_throbber';alert('I am up to here');
// $(div_to_load).hide();// $(div_throbber_id).show();// componentdemo_ajaxSetup();// $(div_to_load).load('/nagiosxi/includes/components/componentdemo/componentdemo_misc.php?request=hosts',// function() {// $(div_throbber_id).hide();// $(div_to_load).show();// } // End function() {// ); // End $(div_to_load).load(
} // End function populate_hosts() {
Quick Break
Have A Look At These
AJAX Dependent
Wizards / Components / Dashlets
EMC CLARiiON Monitoring Wizard
Performance Data Tool
Highcharts
Ping Action & Traceroute Action
Google Maps Component & Dashlet
Birdseye
Conclusion
● Don't become a baldness statistic● Keep that lovely head of hair by knowing
JavaScript/jQuery coding techniques● Learn by
experimenting … take baby steps
● Go forth and create awesome Nagios XI add-ons!
Questions?
Any questions?
Thanks!