Ubidots Developer Guides
Help CenterAPI ReferenceData APICommunity
  • Welcome to our Dev Guides
  • ⚡️ Getting Started
    • What is Ubidots?
    • Devices, Variables, and Dots
    • Technical FAQs
    • Business FAQs
  • 🧩Integration Guides
    • Industrial IoT
      • Advantech
      • Amplified Engineering
      • AWS
      • Azimut
      • Balena
      • Bivocom
      • CESVA
      • Controllino
      • Digital Communications Technologies (DCT)
      • Everactive
      • Golioth
      • Kepware
      • Kunbus
      • Monnit
      • MultiTech
      • NCD.io
      • Node-RED
      • Omicron IoT
      • Red Lion
      • Robustel
      • Senquip
      • Sielco
      • Siemens
      • Strega
      • vNode
      • WAGO
      • Weintek
      • YuDash
    • Cellular
      • Blues Wireless
      • Digi International
      • Hologram
      • Monogoto
      • Particle
      • Quectel
      • Soracom
    • LoRaWAN
      • AonChip
      • Chirpstack
      • Decentlab
      • Helium
      • ioThings
      • LORIOT
      • Milesight
      • MOKOSmart
      • RAKwireless
      • Sagemcom
      • Seeed Studio
      • Senet
      • The Things Industries
        • The Things Stack
        • The Things Network
    • Sigfox
      • Digital Matter
      • McThings
      • Sigfox
      • Suntech
      • Thinxtra
      • UnaBiz
    • Satellite
      • Swarm
    • Dev Kits
      • Adafruit
      • Advantech
      • AloriumTech
      • Arduino
      • Blues Wireless
      • DFRobot
      • Dragino
      • Electric Imp
      • Espressif Systems
      • McThings
      • Microchip Technology
      • Onion
      • Particle
      • Pycom
      • RAKwireless
      • Raspberry Pi
      • Seeed Studio
      • Sodaq
      • STMicroelectronics
      • Texas Instruments
      • Thinxtra
      • Verse Technology
    • Weather
      • Weather Plugins
      • Ambient Weather
    • Tools
      • Gambit Communications
      • PubNub
  • 📊Dashboards & Widgets
    • HTML Canvas
      • 3rd party packages
      • Preload Dashboard data
      • Built-in library
        • Properties
        • Methods
        • Listening events
        • API
      • Examples
        • Basics
        • Create an LCD screen with the HTML Canvas
        • Interacting with dashboard data
        • Change header's custom style
        • Adding real time using Socket.IO
        • Delete Variable data from a Device
        • Delete Variable data from Groups or Types of Devices
        • Navigation through Dashboard
        • Using a React library
      • Code editor
        • HTML Tab
        • CSS Tab
        • JavaScript Tab
    • Custom UI
      • Paragraph
      • Input combo
        • Text
        • Numeric
        • Numeric with buttons
        • Date
        • Time
        • Toggle
        • Dropdown
        • Multiple selection dropdown
      • Button
    • Custom Style
      • Dashboards
      • Widgets
    • Line chart
    • Pages
      • Getting started
      • Development
      • API
        • Page creation
        • Publish
  • 🤖UbiFunctions
    • Getting Started
      • Creating an UbiFunction
      • Coding an UbiFunction
      • Testing an UbiFunction
      • Authentication
      • Execution Time
      • Logs
    • Runtimes
      • Python
      • NodeJS
      • Custom Runtimes
    • Invocation
      • Time-based Trigger
      • HTTPS
      • MQTT Publish
      • Ubidots Event
    • Advanced
      • Account Token
      • Execution time
      • Raw Functions
      • CORS Policy
      • Async Execution
      • DaaS (Decoder as a Service)
      • Developing and Managing UbiFunctions with Ubidots CLI
    • Examples
    • Specs and Limits
    • Storage
      • File Storage API
      • Mutiple files
  • 🧩Plugins
    • What is a plugin?
    • Public vs. Private
    • Public plugins
      • Cron
      • Webhook
    • Private Plugins
      • Cron
      • Webhook
      • Widget
      • Device
    • Plugins development
      • Getting started
      • Cron
      • Webhook
      • Widget
      • Device
      • view.xml
      • view_widget.xml
    • Plugins deployment
      • Cron and Webhook
      • Widget
      • Device
    • Using the plugins
      • Cron and Webhook
      • Widget
      • Device
  • 📈SYNTHETIC VARIABLES
    • Getting started
      • Creating synthetic variables
      • Synthetic Variables' editor
    • Expressions
      • Mathematical
      • Date range
      • Rolling
      • Special functions
    • Specs and limits
    • Examples
      • Mathematical
      • Date range
      • Rolling
      • Special functions
  • ⌨️Developer tools
    • Javascript SDK
      • Overview
      • Getting started
      • Ubidots class
        • Get methods
        • Filter methods
        • Ubidots objects
          • Entity object
          • Paginator
      • Examples
    • CLI
      • Overview
      • Installing
      • Usage
      • SDK for UbiFunctions
  • 🏗️Apps
    • App builder
      • Custom sidebar
Powered by GitBook
On this page
  • Example #1
  • Example #2:
  • Example #3:
  • Example #4:

Was this helpful?

Export as PDF
  1. Dashboards & Widgets
  2. HTML Canvas
  3. Examples

Basics

Example #1

This example creates a text box to set a variable's value.

HTML:

<div class="notification--container" id="notification">
  <p>Value sent successfully</p>
</div>

<div class="send-value--container">
  <input type="number" step="0.0001" placeholder="Enter number" class="send-value--input" id="value" />
  <button type="button" class="send-value--button" id="send-value">Send value</button>
</div>

CSS:

.send-value--container {
  	left: 50%;
	position: absolute;
  	top: 50%;
  	transform: translate(-50%, -50%);
}

.send-value--input {
	border: none;
  	border-bottom: 2px solid #28AECD;
  	display: block;
  	margin: 0 auto;
  	font-size: 14px;
  	outline: none;
}

.send-value--button {
  	background: #FFFFFF;
  	border: 2px solid #28AECD;
  	border-radius: 20px;
  	color: #28AECD;
  	font-size: 14px;
	margin-top: 10px;
	width: 100%;
}

.send-value--button:hover {
 	background: #28AECD;
  	cursor: pointer;
  	color: #FFFFFF;
}

.notification--container {
 	display: none;
}

JavaScript:

In the following code, the variable VARIABLE_ID must be set accordingly.

var sendValue = document.querySelector('#send-value');
var value = document.querySelector('#value');
var notification = document.querySelector('#notification');
var TOKEN = ubidots.token;
var VARIABLE_ID = "variable-id";

function postValue(variable, token, callback) {
  var url = 'https://industrial.api.ubidots.com/api/v1.6/variables/' + variable + '/values';
  var headers = {
    'Content-Type': 'application/json',
    'X-Auth-Token': TOKEN 
  };
  
  notification.style.display = 'none';

  fetch(url, {
    method: 'POST',
    headers: headers,
    body: JSON.stringify({ 
      value: parseFloat(value.value, 10) 
    })
  })
  .then(function(response) {
    if (response.ok) {
      return response.json();
    } else {
      throw new Error('Error posting value');
    }
  })
  .then(function(data) {
    callback(data.value);
  })
  .catch(function(error) {
    console.log(error);
  });
}

sendValue.addEventListener('click', function () {
  postValue(VARIABLE_ID, TOKEN, function (value) {
    notification.style.display = 'block';
  });
});

Example #2:

The next example shows how to get data from Ubidots and display it in a Highcharts chart:

HTML:

<div id="container" style="min-width: 310px; height: 310px; margin: 0 auto"></div>

JavaScript:

In the following code, the variable VARIABLE_ID must be set accordingly.

var TOKEN = ubidots.token;
var VARIABLE = 'variable-id';

function makeHttpRequest(url, method, headers, body) {
  return new Promise(function(resolve, reject) {
    fetch(url, {
      method: method,
      headers: headers,
      body: body
    })
    .then(function(response) {
      if (response.ok) {
        return response.json();
      } else {
        throw new Error('Error making HTTP request');
      }
    })
    .then(function(data) {
      resolve(data);
    })
    .catch(function(error) {
      reject(error);
    });
  });
}

async function getDataFromVariable(variable, token, callback) {
  var url = 'https://industrial.api.ubidots.com/api/v1.6/variables/' + variable + '/values';
  var headers = {
    'X-Auth-Token': token,
    'Content-Type': 'application/json'
  };
  
  makeHttpRequest(url, 'GET', headers)
    .then(function(res) {
      callback(res.results);
    })
    .catch(function(error) {
      console.error(error);
    });
}

var chart = Highcharts.chart('container', {
  chart: {
    type: 'line'
  },
  title: {
    text: 'Bring data from Ubidots'
  },
  xAxis: {
    type: 'datetime',
  },
  credits: {
    enabled: false
  },
  series: [{
    data: []
  }]
});

getDataFromVariable(VARIABLE, TOKEN, function(values) {
  var data = values.map(function(value) {
    return [value.timestamp, value.value];
  });
  
  chart.series[0].setData(data);
});

async function makeRequest(url, method, token, payload) {
  var headers = {
    'X-Auth-Token': token,
    'Content-Type': 'application/json'
  };
  var body = null;

  if (payload) {
    body = JSON.stringify(payload);
  }

  return makeHttpRequest(url, method, headers, body);
}

async function sendDataToDevice(sendDataDeviceLabel, token, payload) {
  var url = 'https://industrial.api.ubidots.com/api/v1.6/devices/' + sendDataDeviceLabel + '/';
  var method = 'POST';

  return makeRequest(url, method, token, payload);
}

async function getDeviceVariables(sendDataDeviceID, token) {
  var url = 'https://industrial.ubidots.com/api/v2.0/devices/' + sendDataDeviceID + '/variables';
  var method = 'GET';

  return makeRequest(url, method, token);
}

async function getDashboardDevices(sendDataDashboardID, ubidotsToken) {
  var url = 'https://industrial.ubidots.com/api/-/dashboards/' + sendDataDashboardID + '/devices?sort_by=name&page_size=500';
  var method = 'GET';

  return makeRequest(url, method, ubidotsToken);
}

async function getAllDashboards(ubidotsToken) {
  var url = 'https://industrial.api.ubidots.com/api/v2.0/dashboards/';
  var method = 'GET';

  return makeRequest(url, method, ubidotsToken);
}

async function getAllDevices(token) {
  var url = 'https://industrial.api.ubidots.com/api/v2.0/devices/';
  var method = 'GET';

  return makeRequest(url, method, token);
}

Third party libraries:

https://cdnjs.cloudflare.com/ajax/libs/highcharts/6.1.1/highcharts.js

Example #3:

This example is exactly the same as the one before, but it uses Plotly as a charting library instead of Highcharts:

HTML:

<div id="plotlyDiv" style="width:100%;height:400px;"></div>

JavaScript:

var TOKEN = ubidots.token;
var VARIABLE = 'variable-id';

function makeHttpRequest(url, method, headers, body) {
  return new Promise(function(resolve, reject) {
    fetch(url, {
      method: method,
      headers: headers,
      body: body
    })
    .then(function(response) {
      if (response.ok) {
        return response.json();
      } else {
        throw new Error('Error making HTTP request');
      }
    })
    .then(function(data) {
      resolve(data);
    })
    .catch(function(error) {
      reject(error);
    });
  });
}

function getDataFromVariable(variable, token, callback) {
  var url = 'https://industrial.api.ubidots.com/api/v1.6/variables/' + variable + '/values';
  var headers = {
    'X-Auth-Token': token,
    'Content-Type': 'application/json'
  };

  makeHttpRequest(url, 'GET', headers)
    .then(function(res) {
      callback(res.results);
    })
    .catch(function(error) {
      console.error(error);
    });
}

var layout = {
  xaxis: {
    type: 'date',
    title: 'Date'
  },
  yaxis: {
    title: 'Value'
  },
  title: 'My Variable'
};

Plotly.plot('plotlyDiv', [], layout);

getDataFromVariable(VARIABLE, TOKEN, function(values) {
  var trace = {
    x: [],
    y: [],
    mode: 'lines',
    type: 'scatter',
    name: '2000'
  };
  values.forEach(function(value) {
    trace.x.push(value.timestamp);
    trace.y.push(value.value);
  });

  Plotly.addTraces('plotlyDiv', trace);
});

Third party libraries:

https://cdnjs.cloudflare.com/ajax/libs/plotly.js/1.39.4/plotly.min.js

Example #4:

This example uses the HTML Canvas widget to turn on/off a dashboard's "real time":

HTML:

<div class="notification--container" id="notification">
	<p>Dashboard Real Time</p>
</div>
<div class="real-time--container">
	<button type="button" class="real-time--button" id="real-time">Enable real time</button>
</div>

CSS:

.real-time--container {
left: 50%;
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
}

.real-time--button {
background: #FFFFFF;
border: 2px solid #28AECD;
border-radius: 20px;
color: #28AECD;
font-size: 20px;
margin-top: 10px;
width: 100%;
}

.real-time--button:hover {
background: #28AECD;
cursor: pointer;
color: #FFFFFF;
}

.notification--container {
display: none;
}

JavaScript:

var realTime = document.getElementById('real-time');
var notification = document.getElementById('notification');

realTime.addEventListener('click', function() {
  ubidots.setRealTime(true);
  notification.style.display = 'block';
});

PreviousExamplesNextCreate an LCD screen with the HTML Canvas

Last updated 1 year ago

Was this helpful?

📊