-->
Page 1 of 1

How to use ajax on an ESP8266 HTML webpage served w/Arduino

PostPosted: Wed Apr 13, 2016 4:45 pm
by Th3On3Fr33man
I have been recently learning how to program in Arduino to host a HTML/CSS/Javascript webpage on an Adafruit HUZZAH ESP8266 breakout chip, so please forgive me if my methods here are completely off.

I'm currently trying to get a value to automatically update via ajax with a javascript function that is using setInterval to run every five seconds. And while it does update the value at least one time, it takes far longer than five seconds to do so, and then it never updates the value again.

Please let me know what you think of the way I'm currently trying to implement this, and if I'm way off the mark? To help you navigate the key functions are loadNum() and sendNum(); and the variable that's incrementing is testNumPart2 (there's also more code on here as well that uses a button to turn an LED on/off).

Thanks!

Code: Select all#include <ESP8266WiFi.h>

#define LED_PIN  15  // This example assumes you have a LED connected to pin 13

const char* ssid = "REDACTED";
const char* password = "REDACTED";

// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  delay(10);

  // prepare GPIO2
  pinMode(LED_PIN, OUTPUT);
  //digitalWrite(2, 0);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
boolean currentLineIsBlank = true;
String currentLine = "";
String LEDstatus = "off";

String testNumPart1 = "document.getElementById('demo').innerHTML = ";
int testNumPart2 = 23;

String testNum = testNumPart1 + testNumPart2;

//Serial.print("TEST: ");
//Serial.println(testNum);

while (client.connected()) {
  if (client.available()) {
    char c = client.read();
    Serial.write(c);

    testNumPart2++;

    testNum = testNumPart1 + testNumPart2;

    // if you've gotten to the end of the line (received a newline
    // character) and the line is blank, the http request has ended,
    // so you can send a reply
    if (c == '\n' && currentLineIsBlank) {
      // send a standard http response header
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println("Connection: close");  // the connection will be closed after completion of the response
      //client.println("Refresh: 5");  // refresh the page automatically every 5 sec
      client.println();
      client.println("<!DOCTYPE HTML>");
      client.println("<html>");
        client.println("<head>");
            client.println("<title>Adafruit HUZZAH ESP8266</title>");
            client.println("<style type='text/css'>");

                //Styles for on/off switch
                client.println(".onoffswitch { position: relative; width: 90px; -webkit-user-select:none; -moz-user-select:none; -ms-user-select: none; }");
                client.println(".onoffswitch-checkbox { display: none; }");
                client.println(".onoffswitch-label { display: block; overflow: hidden; cursor: pointer; border: 2px solid #999999; border-radius: 20px; }");
                client.println(".onoffswitch-inner { display: block; width: 200%; margin-left: -100%; transition: margin 0.3s ease-in 0s;}");
                client.println(".onoffswitch-inner:before, .onoffswitch-inner:after { display: block; float: left; width: 50%; height: 30px; padding: 0; line-height: 30px; font-size: 14px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold; box-sizing: border-box; }");
                client.println(".onoffswitch-inner:before { content: 'ON'; padding-left: 10px; background-color: #34A7C1; color: #FFFFFF; }");
                client.println(".onoffswitch-inner:after { content: 'OFF'; padding-right: 10px; background-color: #EEEEEE; color: #999999; text-align: right; }");
                client.println(".onoffswitch-switch { display: block; width: 18px; margin: 6px; background: #FFFFFF; position: absolute; top: 0; bottom: 0; right: 56px; border: 2px solid #999999; border-radius: 20px; transition: all 0.3s ease-in 0s; }");
                client.println(".onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner { margin-left: 0; }");
                client.println(".onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch { right: 0px; }");
            client.println("</style>");

            //Javascript Function
            client.println("<script>");
                client.println("function LEDswitch(){");
                    client.println("var LEDswitchCheck = document.getElementById('myonoffswitch').checked;");

                    client.println("if(LEDswitchCheck){");
                        client.println("window.location.href = '/H';");
                    client.println("}");
                    client.println("else {");
                        client.println("window.location.href = '/L';");
                    client.println("}");
                client.println("}");
                client.println("function loadNum() {");
                    client.println("setInterval(sendNum, 5000);");
                client.println("}");
                client.println("function sendNum() {");
                    client.println("var request = new XMLHttpRequest();");
                    client.println("request.onreadystatechange = function() {");
                        client.println("if (this.readyState == 4) {");
                            client.println("if (this.status == 200) {");
                                client.println(testNum);
                            client.println("}");
                        client.println("}");
                    client.println("};");
                    client.println("request.open('GET', '', true);");
                    client.println("request.send();");
                client.println("}");
            client.println("</script>");

        client.println("</head>");
        client.println("<body style='background-color:#558C89;' onload=\"loadNum()\">");
            client.println("<div style='background-color:#74AFAD;'>");
                client.println("<h1 style='text-decoration: underline;'>Adafruit HUZZAH ESP8266</h1>");
            client.println("</div>");

    }
    if (c == '\n') {
      // you're starting a new line
      currentLineIsBlank = true;

      // if the current line is blank, you got two newline characters in a row.
      // that's the end of the client HTTP request, so send a response:
      if (currentLine.length() == 0) {
        client.println("<div style='background-color:#74AFAD;'>");
            client.println("<h2 style='color: red;'>LED Controls</h2>");

        // The HTTP response ends with another blank line:
        client.println();

                        client.println("<div class='onoffswitch'>");

                            if (LEDstatus == "on")
                            {
                                client.println("<input type='checkbox' name='onoffswitch' class='onoffswitch-checkbox' id='myonoffswitch' checked='checked' onclick='LEDswitch()'>");


                            } //end if
                            else if(LEDstatus == "off")
                            {
                                client.println("<input type='checkbox' name='onoffswitch' class='onoffswitch-checkbox' id='myonoffswitch' onclick='LEDswitch()'>");
                            } //end else

                            client.println("<label class='onoffswitch-label' for='myonoffswitch'>");
                                client.println("<span class='onoffswitch-inner'></span>");
                                client.println("<span class='onoffswitch-switch'></span>");
                            client.println("</label>");
                        client.println("</div>");
                    client.println("</div>");
                    client.println("<div style='background-color:#74AFAD;'>");
                        client.println("<h2 style='color: green;'>Num Refresh Test</h2>");
                        client.println("<div id='demo'><h2>Let AJAX change this text</h2></div>");
                        //client.println("<button type='button' onclick='loadNum()'>Change Content</button>");
                    client.println("</div>");
                client.println("</div>");
            client.println("</body>");
        client.println("</html>");
        break;
      } //end if

      else
      {
          currentLine = "";
      } //end else
    }
    else if (c != '\r') {
      // you've gotten a character on the current line
      currentLineIsBlank = false;

      currentLine += c;
    }

    // Check to see if the client request was "GET /H" or "GET /L":
    if (currentLine.endsWith("GET /H")) {
      digitalWrite(LED_PIN, HIGH);               // GET /H turns the LED on
      LEDstatus = "on";
    } //end if (/H)

    if (currentLine.endsWith("GET /L")) {
      digitalWrite(LED_PIN, LOW);                // GET /L turns the LED off
      LEDstatus = "off";
    } //end if (/L)

  } //end if (client available)
} //end while
// give the web browser time to receive the data
delay(1);

// close the connection:
client.stop();
Serial.println("client disconnected");
} //end if (client)
} //end void loop

Re: How to use ajax on an ESP8266 HTML webpage served w/Ardu

PostPosted: Tue Apr 19, 2016 8:19 am
by Th3On3Fr33man
Alright, well I ended up using this as a basis and it worked out: viewtopic.php?f=29&t=7059