-->
Page 1 of 3

help with Javascript needed

PostPosted: Thu Jun 11, 2020 5:39 pm
by Luc Volders
I hate to admit it but I do have a problem which I have been looking at for some weeks and just do not find an answer for.

What I want to do is to have an ESP8266 send sensor data to a computer.
Now the ESP can run a web-server which sends javascript code to the webpage and that is that.
That works and is standard procedure.
But that is not what I want.

I want a webpage with some Javascript that adresses an ESP8266 and gets data from it.
That way I can get data from multiple ESP's.

I found some Json webserver code:

Code: Select all#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
 
ESP8266WebServer server(80);
 
const char* ssid = "ROUTERNAME";
const char* password = "PASSWORD";
 
const char * swaggerJSON = "Swagger JSON API specification";
const char * swaggerUI = "Swagger UI HTML code";
const char * answer = "[{\"value\":\"10.5\",\"timestamp\":\"22/10/2017 10:10\"},{\"value\":\"11.0\",\"timestamp\":\"22/10/2017 10:20\"}]";
 
void setup() {
 
    Serial.begin(115200);
    WiFi.begin(ssid, password);  //Connect to the WiFi network
 
    while (WiFi.status() != WL_CONNECTED) {  //Wait for connection
        delay(500);
        Serial.println("Waiting to connect...");
    }
 
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());  //Print the local IP
 
    server.on("/temperature", handleTemperature);
    server.on("/swagger.json", handleSwaggerJson);
    server.on("/swaggerUI", handleSwaggerUI);
 
    server.begin(); //Start the server
    Serial.println("Server listening");
 
}
 
void loop() {
    server.handleClient(); //Handling of incoming requests
}
 
void handleTemperature() {
    server.send(200, "application/json", answer);
}
 
void handleSwaggerJson() {
     server.send(200, "application/json", swaggerJSON);
}
 
void handleSwaggerUI() {
      server.send(200, "text/html", swaggerUI);
}


Upload this code to an ESP8266 and then wait till it resets. Then open a browser window on your computer and enter:

XXX.XXX.XXX.XXX/temperature

and you will get the JSON code back with the value and timestamp. So this is ok.

Now I want a webpage with some Javascript code that gets that value and displays it in the console
or makes a variable from itr or whatever.

Here is my attempt:

Code: Select all<!DOCTYPE html>
<html>
<body>

<h2>Button test with GET to ESP8266</h2>
<button onclick="putLampOn()">Lamp ON</button>
<br>
<br>
<p>================================================</p>

<script>
function putLampOn() {
  var xhttp = new XMLHttpRequest();
  xhttp.open("GET", "HTTP://192.168.1.80/temperature", true);
  xhttp.send();

xhttp.onreadystatechange = function() {

    if (this.readyState == 4) {
       // Typical action to be performed when the document is ready:
       alert( xhttp.responseText);
       alert(JSON.stringify(this.responseText));
       alert("testje ", JSON.stringify(this.responseText));
    };
}
</script>
 
</body>
</html>


I can not get this to work.

The idea is that I can use this with multiple GET commands to multiple ESP's
and then make a nice looking webpage that displays all kinds off values for an
home automation system.

Another command that Javascript uses is Fetch.

Code: Select all<!DOCTYPE html>
<html>
<body>

<h2>Button test with GET</h2>


<button onclick="putLampOn()">Lamp ON</button>
<br>
<br>
<p>================================================</p>

<script>
function putLampOn()
  {
fetch("HTTP://192.168.1.80/temperature")
.then(response => response.json())
.then(data => {alert('Success:', data[0])});
  }
}

</script>
 
</body>
</html>


Also not working.

is there a Javascript expert here who can give me the right code to get the vaule out of the ESP8266.

Luc

Re: help with Javascript needed

PostPosted: Thu Jun 11, 2020 7:24 pm
by davydnorris
What do you see in the web browser console? Anything useful?

I can see some immediate issues in your first example - Javascript is single threaded, so you have to set the event handler before you need it. I've also added a check for the response:

Code: Select all<!DOCTYPE html>
<html>
<body>

<h2>Button test with GET to ESP8266</h2>
<button onclick="putLampOn()">Lamp ON</button>
<br>
<br>
<p>================================================</p>

<script>
function putLampOn() {
  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function() {
    if (this.readyState === 4) {
      if (this.status === 200) {
        // Typical action to be performed when the document is ready:
        alert(this.responseText);
        alert(JSON.stringify(this.responseText));
        alert("testje ", JSON.stringify(this.responseText));
      } else {
        alert(this.status);
      }
    };
  };

  xhttp.open("GET", "HTTP://192.168.1.80/temperature", true);
  xhttp.send();

}
</script>
 
</body>
</html>

Re: help with Javascript needed

PostPosted: Fri Jun 12, 2020 4:29 am
by Luc Volders
Thanks for your help !!
I tried your code and the only thing that I got back was an alert saying 0

So I started commenting out all the alerts and then it made clear that the only alert
that was working was the one in the else part of the if statement, and that is the status.

So none of the alerts were giving any information........

So I altered the script in:

Code: Select all<script>
function putLampOn()
{
  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function()
  {
    //if (this.readyState === 4)
    //{
      if (this.status === 200)
      {
        // Typical action to be performed when the document is ready:
        //alert(this.responseText);
        //alert(JSON.stringify(this.responseText));
        //alert("testje ", JSON.stringify(this.responseText));
        alert("test");
      } else
        {
        alert(this.status);
        };
     //};
};

  xhttp.open("GET", "HTTP://192.168.1.80/temperature", true);
  xhttp.send();

}
</script>


and even the alert("test") was nor responding.

The console says:
Cross-Origin-aanvraag geblokkeerd:
Cross origine blocked

Same origine policy prohibits reading external source

Reden: CORS-header ‘Access-Control-Allow-Origin’ ontbreekt
Reason: CORS-header ‘Access-Control-Allow-Origin’ is missing.........

Luc

Re: help with Javascript needed

PostPosted: Fri Jun 12, 2020 8:45 am
by davydnorris
I actually suspected that was the problem at the start, but there were errors in the code that needed to be fixed first.

This is part of web security to prevent XSS attacks, and you need to add some headers to explicitly tell your browser that these IP addresses are OK. See this:

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

You need to actually set some headers on your ESP server, to tell the browser it's OK. In your ESP code, add the following line before every response is sent:

Code: Select allserver.sendHeader("Access-Control-Allow-Origin", "*");