The use of the ESP8266 in the world of IoT

User avatar
By V3N0MX
#84464 Hello everyone,

I have a full functional website for a DHT22 sensor (thermostat) which I made only using simple HTML code and I am trying to improve the webserver communication by replacing the old school HTML with AJAX so whenever I send a command I don't have to refresh the page or change the page. I have to mention that I don't know JavaScript but I'm trying to understand the code.


the simple code I'm using is:

Code: Select allvoid handleSave() {
  String str = "Settings Saved ...\r\n";

  Serial.print("number of arguments ");
  Serial.println(webserver.args());                    // number of arguments
if (webserver.args() > 0 ) {
    for ( uint8_t i = 0; i < webserver.args(); i++ ) {
      str += webserver.argName(i) + " = " + webserver.arg(i) + "\r\n";

      Serial.println("Arg " + String(i) + "=" + webserver.argName(i));
      Serial.println("Arg " + String(i) + "=" + webserver.arg(i));
    }

    String inString = "";
    inString = (webserver.arg(0));
    settemp = inString.toFloat();
    Serial.print("settemp ");
    Serial.println(settemp);
    Serial.println();
  }
  webserver.send(200, "text/plain", str.c_str());
}


the button and textfield form I'm using is:

Code: Select all page += "<form method='post' action=/save >";
  page += "<b>Temperature Setpoint:<br><input name='settemp' type='text' size='16' value='' ></b><br><br> ";
  page += "<input type='submit' name='Temperature change' value='Accept'><br><br>";
  page += "</form>";


and in void setup I'm using this handling, so when the button is clicked it sends me to the /save page and the value of the variable changes.
Code: Select all  webserver.on("/save", handleSave);


Can someone explain how to implement this with AJAX (GET, SET) so when I complete the text field form with my temp. value and I press on the button there should be no refresh to change the value (also I don't want to leave the main page, just to change a variable in the code). I tried some scripts and some functions but no succes so far, all the tutorials on the internet follow a simple boolean for an LED switching ON/OFF . Any explanation about text forms would be appreciated :shock:

Thank you in advance!
User avatar
By quackmore
#84469 Hi
have a look to this quick and dirt example
it uses Bootstrap and jQuery to make everything easy

the key points:
1- you mark your html element with an id and then you use jQuery $('#id').text(value) (eventually .val()) to update the value (the example call an update function every minute)
2- you obtain the required information from your device using ajax: $.ajax(...)
3- your device will provide some kind of APIs for punctual information, for instance the example assume that when asked "GET /api/temperature" your device will answer with some json like this {"temperature": 20}

googling bootstrap and jquery will provide plenty of examples and code snippets

hope this will help

Code: Select all<!doctype html>
<html lang="en">

<head>
  <title>Title</title>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>

<body class="bg-secondary  col-sm-6 mx-auto">
 
  ... your html ...

  <div class="d-inline col-sm-4 h4 my-auto" id="temperature">temperature_value_will_be_shown_here</div>
 
  ...

  <!-- JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS, then custom script -->
  <!-- don't use slim if you need ajax -->
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
    integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
    integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
    crossorigin="anonymous"></script>
  <script src="script.js"></script>
</body>

</html>

// script.js

setInterval(update_temperature, 60000);

function update_temperature() {
  $.ajax({
    type: 'GET',
    url: '/api/temperature',
    dataType: 'json',
    success: function (data) {
      $("#temperature").text(data.temperature);
    },
    error: function (xhr) {
      alert("update_temperature got: " + xhr.responseText);
    }
  });
}