Hi there. I have an agent running and getting data from an imp.
I want to use a javascript page from a web server, that requests for the sensor values from the agent.
Is there an example of javascript that shows how to request a URL from Agent, and have the response (in my case its just text), be shown within the inner HTML. After being able to receive the response from Agent, I can save the response and use it in different places in my web-server javascript. I think this is an AJAX request/response from Javascript.
The one problem I think I don’t know either way is: would a Javascript from a website be allowed to request a URL to the Agent - the cross-domain issue and how to correctly do this.
I made a countdown project using ajax with the agent, although I host the HTML code on the agent itself, so no cross domain issues.
Thats jQuery, which I loaded from the CDN.
On the Agent there dont need to be any magic, just return a text.
I do a bit more in that I ask the imp for a result and then return that result in the ajax reply, but its a bit too slow to run every second.
I created a sample for you that will periodically poll your agent from a web page to retrieve your sensor values. Instead of retrieving the sensdata object values one at a time, the agent returns the complete JSON encoded object to the html page. The html page updates fields dynamically based on the current values in sensdata.
The agent code also fixes the cross-domain issue
Agent Code:
`
sensdata <- { hw=0, vdda=1 };
http.onrequest(function(request, response) {
// Needed to avoid Access-Control-Allow-Origin header error due to AJAX browser security requirements
// that only allows requests from the domain that served the web page
response.header( “Access-Control-Allow-Origin”, “*” );
if( request.method==“OPTIONS” )
{
response.header(“Access-Control-Allow-Methods”, “POST, GET, OPTIONS”);
response.header(“Access-Control-Allow-Headers”, “origin, x-csrftoken, content-type, accept”);
response.send(200,“OK”);
return;
}
And the HTML page. Since your HTML page is small, you could serve it from the agent itself if you wanted to avoid hosting your HTML page on another server.
`
I do think having the code on Agent is good to get started. In the end I would like to have a “local app” on a mobile phone that uses localStorage for keeping data for 60 days.
@controlCloud - thanks those are very helpful. I just printed them out to study, it is bit advanced for a noobie on JS. I need a few books and another 8 hours in a day to catch up if ever that were possible!
@deonsmt - many salutes to you. Going to try this out in the next couple of days.