-->
Page 1 of 1

Ajax for Webserver on ESP8266

PostPosted: Mon Aug 31, 2015 6:41 am
by MajorMadness
Hi there,
for a Projekt I had to submit data from Website to ESP without reloading the page. Normally I would do this by JQuery, but because there is no Internet connection and I didn't want to include the hole Framework I went back to basics.
So here is a lil snippit if somebody else needs this:
Code: Select allvoid htmlLight() {String site;
/* First part is just for debug */
  site+=F("<script>function reqListener () {\n\r");
  site+=F("  console.log(this.responseText);\n\r");
  site+=F("}\n\r");
/* Function to send data to server */
  site+=F("function ajaxValue(newValue, num) {\n\r");
  site+=F("var url = \"/a_led?n=\" + num + \"&v=\" + newValue;\n\r"); // Change url to fit your needs
  site+=F("var oReq = new XMLHttpRequest();\n\r");
  site+=F("oReq.addEventListener('load', reqListener);\n\r"); // Debugging output console
  site+=F("oReq.open(\"get\", url, true);\n\r");
  site+=F("oReq.send();\n\r");
  site+=F("document.getElementById('val' + num).innerHTML = newValue;\n\r");
  site+=F("}\n\r</script>");
  server.sendContent(site);

This makes it possible to send value to ESP, in my case a slider (in Code named sliderVal[] Array of 16 floats):
Code: Select all  server.sendContent(F("<table><tr>"));
  for (byte i = 0; i < 16; i++) {
    site="";
    site+=F("<td><input type='range' orient='vertical' min='0' max='100' name='led_sl");
    site+= i;
    site+=F("' value='");
    site+= sliderVal[i];
    site+=F("' step='0.1' oninput='ajaxValue(this.value,");
    site+= i;
    site+=F(")'></td>");
    server.sendContent( site);
  }
  server.sendContent(F("</tr><tr>"));
  for (byte i = 0; i < 16; i++) {
    site="";
    site+=F("<td><span id='val");
    site+= i;
    site+=F("'>");
    site+= sliderVal[i];
    site+=F("</span></td>");
    server.sendContent( site);
  }
  server.sendContent(F("</tr></table><a href='/' class='buttonL'>Back</a>"));
 // server.send(200, "text/html", site);
}

To handle the request:
Code: Select allvoid a_led() {
  Serial.println( "Slider Arg: ");
  Serial.println( server.args());
  for (uint8_t i=0; i<server.args(); i++){
    Serial.println(server.argName(i) + ": " + server.arg(i));
  }
  setSlider(server.arg("n").toInt(),server.arg("v").toFloat());
}

Don't forget:
Code: Select all  server.on("/a_led", a_led);

Cheers