help with ESP8266 and javascript

Hello all,

based on another example I am trying to program an ESP8266 with javascript interface.

I want to have a button to open or close an electronic locker. If locker is open then pushing button with close it and the opposite.
If locker is on for more than 3 seconds then will close automatically.
Javascript make GET requests to have anytime from any client the real state of locker.
But when I push the button only CLOSE commant seems to be sent and I don't know why.
Plz help.
Thanks in advance

nodemcu code

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

#include "index.h" //Our HTML webpage contents with javascripts

#define LED 2  //On board LED

//SSID and Password of your WiFi router
const char* ssid = "Panagiotis_MikroTik-35F62D";
const char* password = "panos0342!";
String DOOR_STATE = "";
unsigned long door_open_interval = 3000;
unsigned long door_open_momment = 0;
unsigned long door_open_past_interval = 0;

ESP8266WebServer server(80); //Server on port 80

//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void handleRoot() {
  String s = MAIN_page; //Read HTML contents
  server.send(200, "text/html", s); //Send web page
}

void check_DOOR() {
  int a = digitalRead(LED);// or any other pin
  if ( a == LOW) {
    DOOR_STATE = "OPEN";
    door_open_momment = millis();
  }
  else
  {
    DOOR_STATE = "CLOSE";
  }

  server.send(200, "text/plane", DOOR_STATE); //Send Led State value only to client ajax request
}

void handleDOOR() {

  String t_state = server.arg("DOOR_STATE"); //Refer  xhttp.open("GET", "setDOOR?DOOR_STATE="+doorState, true);
  Serial.println(t_state);
  if (t_state == "OPEN")
  {
    digitalWrite(LED, LOW); //LED ON
    DOOR_STATE = "OPEN"; //Feedback parameter
  }
  else
  {
    digitalWrite(LED, HIGH); //LED OFF
    DOOR_STATE = "CLOSE"; //Feedback parameter
  }

  server.send(200, "text/plane", DOOR_STATE); //Send web page
}
//==============================================================
//                  SETUP
//==============================================================
void setup(void) {
  Serial.begin(115200);

  WiFi.begin(ssid, password);     //Connect to your WiFi router
  WiFi.mode(WIFI_STA);
  Serial.println("");

  //Onboard LED port Direction output
  pinMode(LED, OUTPUT);
  digitalWrite(LED, HIGH); //LED OFF this only is for build in LED for other pin in HIGH
  DOOR_STATE = "CLOSE";

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP

  server.on("/", handleRoot);      //Which routine to handle at root location. This is display page
  server.on("/setDOOR", handleDOOR);
  server.on("/checkDOOR", check_DOOR);

  server.begin();                  //Start server
  Serial.println("HTTP server started");
}
//==============================================================
//                     LOOP
//==============================================================
void loop(void) {
  if ((DOOR_STATE = "OPEN") && ((millis() - door_open_momment) >= door_open_interval)) {
    digitalWrite(LED, HIGH); //LED OFF this only is for build in LED for other pin in HIGH
    DOOR_STATE = "CLOSE";
  }// check for open door and if it is open for more that door_open_interval close it

  server.handleClient();          //Handle client requests
}

javascript code

const char MAIN_page[] PROGMEM = R"=====(
<!DOCTYPE html>
<html>
  <head>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'/>
    <meta charset='utf-8'>
    <style>
      body {font-size:140%;} 
      #main {display: table; margin: auto;  padding: 0 10px 0 10px; } 
      h2 {text-align:center; } 
      #DOOR_button { padding:10px 10px 10px 10px; width:100%;  background-color: #50FF50; font-size: 120%;}
    </style>
    <script>
    var doorState = "___"
      function switchDOOR() {
        var xhttp = new XMLHttpRequest();
        if (doorState=="CLOSE"){
              doorState="OPEN";
            }
        if (doorState == "OPEN"){
              doorState = "CLOSE";
            }

        xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
            if (doorState=="CLOSE"){
              document.getElementById("DOOR_button").value = "OPEN DOOR";
              document.getElementById("DOOR_button").backgroundColor = "#FF0000";
              doorState="OPEN";

            }
            if (doorState=="OPEN"){
              document.getElementById("DOOR_button").value = "CLOSE DOOR";
              document.getElementById("DOOR_button").backgroundColor = "#50FF50";
              doorState="CLOSE";
            }
          }
        };
        document.getElementById("doorstate").innerHTML = doorState;
        xhttp.open("GET", "setDOOR?DOOR_STATE="+doorState, true);
        xhttp.send();
      }

      setInterval(function() {
      // Call a function repetatively with 2 Second interval
        getDoorState();
      }, 500); //500mSeconds update rate

      function getDoorState() {
          var xhttp = new XMLHttpRequest();
          xhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
              doorState =this.responseText;
            }
          if (doorState=="CLOSE"){
              document.getElementById("DOOR_button").value = "OPEN DOOR";
              document.getElementById("DOOR_button").backgroundColor = "#50FF50";
           }
          if (doorState=="OPEN"){
              document.getElementById("DOOR_button").value = "CLOSE DOOR";
              document.getElementById("DOOR_button").backgroundColor = "#FF0000";
            }
          };
          xhttp.open("GET", "checkDOOR", true);
          xhttp.send();
        }


</script>

    <title>DOOR CONTROL</title>
    <span id="doorstate">NA</span>
    <span id="test1">NA</span>
    <span id="test2">NA</span>
  </head>
<body>
<div id='main'>
  <h2>DOOR Control</h2>
  <input type="button" id = "DOOR_button" onclick="switchDOOR()" value="doorState"       />
</div>


</body>
</html>
)=====";

Not the problem, but "text/plane" should be "text/plain" throughout your code

In the nodemcu code:

void loop(void) {
  if ((DOOR_STATE = "OPEN") && ((millis() - door_open_momment) >= door_open_interval)) {
...

you are assigning to DOOR_STATE, not comparing (== vs. = )

In your javascript code

        if (doorState=="CLOSE"){
              doorState="OPEN";
            }
        if (doorState == "OPEN"){
              doorState = "CLOSE";
            }

This will always result in doorState being set to "CLOSE" -- did you mean to do this or should these be an else() clause?

adout nodemcu code you are right I didn't see it.

about javascript code.
I want any time pushing the button the door state to change that is the reason about these if statements

If DOOR_State == "OPEN" make it "CLOSE" and send the state to the nodemcu and if DOOR_State == "CLOSE" make it "OPEN" and send the state to the nodemcu. I can't understand my fault on this.

Thanks for you reply

panagiotispir:
adout nodemcu code you are right I didn't see it.

about javascript code.
I want any time pushing the button the door state to change that is the reason about these if statements

If DOOR_State == "OPEN" make it "CLOSE" and send the state to the nodemcu and if DOOR_State == "CLOSE" make it "OPEN" and send the state to the nodemcu. I can't understand my fault on this.

Thanks for you reply

But that is not what the code does. For example, DOOR_State is CLOSE. The first if statement is true so it executes the statement DOOR_State = OPEN. Then it moves on to the next statement which is the second if statement. It checks to so if DOOR_State is OPEN which is it, so it executes DOOR_Statement = "CLOSE"
This means the variable DOOR_State will always be "CLOSE".

You need to re-think your logic.

Yeap you are right, I didn't realize this.
Thanks a lot!
I use another way to get the job done and I am uploading the code in case that someone else want to use it.

nodemcu code

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

#include "index.h"

char ssid[] = "Panagiotis_MikroTik-35F62D";       //  your network SSID (name)
char pass[] = "panos0342!";          //  your network password

ESP8266WebServer server(80);

 
String request = "";
//int LED_Pin = D1;
int LED_Pin = 2;
String DOOR_STATE = "CLOSE";
unsigned long door_open_interval = 6000;
unsigned long door_open_momment = 0;
unsigned long door_open_past_interval = 0;

void handleRoot() {
  String s = MAIN_page; //Read HTML contents
  server.send(200, "text/html", s); //Send web page
}

void open_door(){
  digitalWrite(LED_Pin, LOW);
  DOOR_STATE = "OPEN";
  door_open_momment=millis();
  server.send(200, "text/plain", DOOR_STATE);
}
void close_door(){
  digitalWrite(LED_Pin, HIGH);
  DOOR_STATE = "CLOSE";
  server.send(200, "text/plain", DOOR_STATE);
}
void check_door(){
  server.send(200, "text/plain", DOOR_STATE);
}
 
void setup() 
{
    pinMode(LED_Pin, OUTPUT);  
    digitalWrite(LED_Pin, HIGH);   
    
    Serial.begin(115200);
    Serial.println();
    Serial.println("Serial started at 115200");
    Serial.println("ESP8266_LED_CONTROL_AJAX_02");
    Serial.println();
 
    // Connect to a WiFi network
    Serial.print(F("Connecting to "));  Serial.println(ssid);
    WiFi.begin(ssid, pass);
 
    while (WiFi.status() != WL_CONNECTED) 
    {
        Serial.print(".");
        delay(500);
    }
      
    Serial.println("");
    Serial.println(F("[CONNECTED]"));
    Serial.print("[IP ");              
    Serial.print(WiFi.localIP()); 
    Serial.println("]");
 
    // start a server
    server.begin();
    Serial.println("Server started");

  server.on("/", handleRoot);      //Which routine to handle at root location. This is display page
  server.on("/DOOROPEN", open_door);
  server.on("/DOORCLOSE", close_door);
  server.on("/checkDoorState", check_door);
  

 
} // void setup()


void loop(void) {
    if ((DOOR_STATE == "OPEN") && ((millis() - door_open_momment) >= door_open_interval)) {
    digitalWrite(LED_Pin, HIGH); //LED OFF this only is for build in LED for other pin in HIGH
    DOOR_STATE = "CLOSE";
  }// check for open door and if it is open for more that door_open_interval close it

  server.handleClient();          //Handle client requests
}

javascript code

const char MAIN_page[]PROGMEM = R"=====(
<!DOCTYPE html>
<html>
 <head>
 <meta name='viewport' content='width=device-width, initial-scale=1.0'/>
 <meta charset='utf-8'>
 <style>
  body {font-size:140%;} 
  #main {display: table; margin: auto;  padding: 0 10px 0 10px; } 
  h2 {text-align:center; } 
  h3 {text-align:center; } 
  #DOOR { padding:10px 10px 10px 10px; width:100%;  background-color: #50FF50; font-size: 120%;}
  
 </style>

<script>
   function switchDOOR() 
  {
       var button_text = document.getElementById("DOOR").value;
     if (button_text=="OPEN DOOR")
     {
       document.getElementById("DOOR").value = "CLOSE DOOR";
       ajaxLoad('DOOROPEN'); 
     }
     else
     {
       document.getElementById("DOOR").value = "OPEN DOOR";
       ajaxLoad('DOORCLOSE');
     }
  }

var ajaxRequest = null;
if (window.XMLHttpRequest)  { ajaxRequest =new XMLHttpRequest(); }
else                        { ajaxRequest =new ActiveXObject("Microsoft.XMLHTTP"); }

var ajaxRequest1 = null;
if (window.XMLHttpRequest)  { ajaxRequest1 =new XMLHttpRequest(); }
else                        { ajaxRequest1 =new ActiveXObject("Microsoft.XMLHTTP"); }


function ajaxLoad(ajaxURL)
{
  if(!ajaxRequest){ alert("AJAX is not supported."); return; }
  
  ajaxRequest.open("GET",ajaxURL,true);
  ajaxRequest.onreadystatechange = function()
  {
    if(ajaxRequest.readyState == 4 && ajaxRequest.status==200)
    {
      var ajaxResult = ajaxRequest.responseText;
      
    }
  }
  ajaxRequest.send();
}

setInterval(function() {
  // Call a function repetatively with 2 Second interval
  getDoorState('checkDoorState');
}, 500); //2000mSeconds update rate

function getDoorState(askfor) {
  if(!ajaxRequest1){ alert("AJAX is not supported."); return; }
  ajaxRequest1.open("GET",askfor,true);
  ajaxRequest1.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var ajaxResult = ajaxRequest1.responseText;
      document.getElementById("door_state").innerHTML =ajaxResult;
    }
    if (ajaxResult=="CLOSE"){
    document.getElementById("DOOR").value = "OPEN DOOR";
    }
  };
  ajaxRequest1.send();
}

</script>

 <title>DOOR CONTROL</title>
</head>
<body>
 <div id='main'>
  <h2>DOOR CONTROL</h2>
  <input type="button" id = "DOOR" onclick="switchDOOR()" value="OPEN DOOR"       /> 
  <h3>Door State:<span id="door_state"></span></h3>
   </div>
   
</body>
</html>
)=====";