Tips or Tutorials using JSON API with Javascript

Hello all.  I've had a hunt around but not seen anything on this subject recently.  

I would like to have a go at grabbing data from my own hosted EmonCMS setup, using a custom webpage with Javascript.  Has anyone written some sample code or snippets explaining the best/easiest way to do this?  

Some samples would be very helpful rather than just pointing out the Javascript function (I've been playing with jQuery getJSON for example).

It would be nice to have an example of retreiving and extracting data elements via the API's feed/list.json, feed/value.json and feed/data.json with the read API key.

Thanks to anyone that can help.

 

Bra1n's picture

Re: Tips or Tutorials using JSON API with Javascript

I've done a little bit so I can display the current weather on a web page but bear in mind you need to enable Cross Domain Requests on your web server if you're displaying the data on a web page in a different domain which may have some security implications. Some javascript functions I use below :

 

id is the id of the html element which will have it's text replaced by the output of the function.

function Tot(feedid,timeInterval,id) //Returns Total for a feedid over timeInterval in minutes
{
d = new Date();
endt = d.valueOf();
startt = endt - (timeInterval * 60 * 1000);
params = "apikey=your_api_key&id=" + feedid;
params = params + "&" + "start=" + startt;
params = params + "&" + "end=" + endt;
params = params + "&dp=800";
data_url = "http://" + raspUrl + "/emoncms/feed/data.json?" + params;
xdata = new XMLHttpRequest();
xdata.open('GET', data_url, true)
xdata.onload = function() {
  res = parsedata(this.responseText).toFixed(2);
  document.getElementById(id).innerHTML = res;
  };
xdata.send();
}

function Current (feedid, id) { //Returns Current Value of a feedid
data_url = "http://" + raspUrl + "/emoncms/feed/value.json?apikey=your_api_key&id=" + feedid;
xdata = new XMLHttpRequest();
xdata.open('GET', data_url, true)
xdata.onload = function() {
  str = this.responseText;
  res = str.replace(/"/g,'');
 
  document.getElementById(id).innerHTML = res;
  };
xdata.send();
}

function parsedata(sdata)
{
//document.write(sdata);
myObject = JSON.parse(sdata);
total = 0;
for (i=0;i<myObject.length;i++){
total = total + parseFloat(myObject[i][1]);
}
return total;
}

Hope this helps, I'm no javascript expert but the above works for me

Bra1n's picture

Re: Tips or Tutorials using JSON API with Javascript

I posted some examples hours ago but they're apparently waiting moderator approval

Keen2bGreen's picture

Re: Tips or Tutorials using JSON API with Javascript

Look forward to reading that Bra1n... Thanks

Bra1n's picture

Re: Tips or Tutorials using JSON API with Javascript

Nothing special just something I cobbled together to display some weather info on a home page (I'm no javascript expert). It may be the inclusion of javascript examples that caused the post to be flagged for a moderator. Be aware that if you want to display data from you server on a web page served from a different domain you'll need to enable cross domain requests on your server which may have security implications.

Paul Reed's picture

Re: Tips or Tutorials using JSON API with Javascript

Code now published above.

Paul - moderator

Bra1n's picture

Re: Tips or Tutorials using JSON API with Javascript

Thanks looks like I left some (commented out) debugging code in there

Bra1n's picture

Re: Tips or Tutorials using JSON API with Javascript

Below are my notes on enabling cross domain requests on Apache, hopefully they won't be too confusing. N.B. I've noticed that while this works for Chrome, Firefox and Safari browsers my version of IE still refuses to display cross domain data :

CORS on Apache
To add the CORS authorization to the header using Apache, simply add the following line inside either the <Directory>, <Location>, <Files> or <VirtualHost> sections of your server config (usually located in a *.conf file, such as httpd.conf or apache.conf), or within a .htaccess file:

a2enmod headers

  Header set Access-Control-Allow-Origin "*"

in /etc/apache2/sites-enabled/000-default
   
To ensure that your changes are correct, it is strongly reccomended that you use

apachectl -t
to check your configuration changes for errors. After this passes, you may need to reload Apache to make sure your changes are applied by running the command
sudo service apache2 reload
or
apachectl -k graceful
.
Altering headers requires the use of mod_headers. Mod_headers is enabled by default in Apache, however, you may want to ensure it's enabled by run

a2enmod headers
Note: you can also use add rather than set, but be aware that add can add the header multiple times, so it's likely safer to use set.

Bra1n's picture

Re: Tips or Tutorials using JSON API with Javascript

This page has some info and a javascript function for cross domain requests that should work with all browsers including IE. I've not got time to modify my functions at the moment as I'm busy building the electronics side of my new weather station

http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/

N.B. you still need to enable it on the server.

Keen2bGreen's picture

Re: Tips or Tutorials using JSON API with Javascript

Many thanks for this Bra1n - a a huge help.

Basically I converted your script into the attached javascript include library that I can call from my custom HTML code.  You'll need to put that somewhere where your HTML code can find it.

Telling the pi to accept calls is a bit of config which basically is:

  1. On your pi run sudo nano /var/www/emoncms/.htaccess and add the line Header set Access-Control-Allow-Origin "*"
  2. Run the command on your pi sudo a2enmod headers 
  3. Then restart apache webserver on your pi with: sudo service apache2 restart

You can quickly test your API is responding from a custom HTML page with (it works by pulling the current value of "your feed id" and inserting it in to the html paragraph "feedid":

If it doesnt work, inspect the page and review the console to check what is causing the problem.  Most often you have the wrong url, API key or CORS is not set properly.

<html>

<script src="<location of your js includes>/EmonCMS.js"></script>

<body>

<p id="feedapi"></p>

<script>

var Emonurl = "http://your-pi-url/emoncms";
var EmonAPIKey = "your-read api";

Current ("your feed id", Emonurl, EmonAPIKey,"feedapi");

</script>

</body>
</html>

 

I should point out - I'm learning JavaScript - I'm no expert, so I can't answer any coding questions.  Hope this is helpful and you find some cool uses for it.

Thank you again Bra1n.

Bra1n's picture

Re: Tips or Tutorials using JSON API with Javascript

Glad to be of help now how about the all browsers including IE version ?

;-)

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.