Go Down

Topic: NodeMCU Webserver (Read 272 times) previous topic - next topic

atifkamal

Hello, I need some help with nodemcu webserver code. I want to submit data from web page form to arduino sketch and the response from sketch to html page. I adopted code from some library example and trying to modifying according to my need. (In code i have changed variables, code is not ok just posting you people to understand the flow. sorry :)


HTML File:

Code: [Select]
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<title>esp</title>
<h6>


Command:
<span id="cmd"></span>
</h6>

<body>
<div style='text-align:left;display:inline-block;width:150px;padding:1px'>




<form id="yform" onsubmit="return transmit(this)">


<button name="led1" value="on">Relay 1 On</button>
<button name="led1" value="off">Relay 1 Off</button>
<br>
<button name="led2" value="on">Relay 2 On</button>
<button name="led2" value="off">Relay 2 Off</button>
<br>
<button name="led3" value="on">Relay 3 On</button>
<button name="led3" value="off">Relay 3 Off</button>
<br>
<button name="led4" value="on">Relay 4 On</button>
<button name="led4" value="off">Relay 4 Off</button>
<br>
<button name="led5" value="on">Relay 5 On</button>
<button name="led5" value="off">Relay 5 Off</button>
<br>
<button name="led6" value="on">Relay 6 On</button>
<button name="led6" value="off">Relay 6 Off</button>
<br>
<button name="led7" value="on">Relay 7 On</button>
<button name="led7" value="off">Relay 7 Off</button>
<br>
<button name="led8" value="on">Relay 8 On</button>
<button name="led8" value="off">Relay 8 Off</button>
<br>

</form>



<script>
function g(i) { return document.getElementById(i) };

function transmit(f) {
if (!xhttp) { //prevent simultaneous requests
xhttp = new XMLHttpRequest();
xhttp.open("POST", "/api");
xhttp.send(f ? (new FormData(f)) : "");
xhttp.onreadystatechange = function () {
if (xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) {
var data = JSON.parse(xhttp.responseText);
g("cmd").innerHTML = data.cmd;
xhttp = null;


}
}
}
return false; //prevent form redirect
}

</script>


Arduino Sketch:
Code: [Select]
  //handles commands from webpage, sends live data in JSON format
  server.on("/api", []() {
    DEBUG_PRINT("server.on /api");
   
    if (server.hasArg("led")) {
      y = server.arg("led");
      DEBUG_PRINT("cmd: " + cmd);
    } //if

    //build json object of program data
    StaticJsonBuffer<200> jsonBuffer;
    JsonObject &json = jsonBuffer.createObject();
   
    json["cmd"] = cmd;

    char jsonchar[200];
    json.printTo(jsonchar); //print to char array, takes more memory but sends in one piece
    server.send(200, "application/json", jsonchar);

  }); //server.on api

atifkamal

No Reply...

Anyways I have changed the code and completed (no more jason).

Juraj

and what works and what doesn't?

Go Up