In this example we learn how to send get request to a web page using NodeMCU or ESP8266? As we know all webpages are HTTP protocols, GET and POST are methods of communicating between web browser and the server. Also we look towards server side php coding. If you are looking for POST method read here.
What is HTTP?
The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers.
HTTP works as a request-response protocol between a client and server. Each Hypertext Transfer Protocol (HTTP) message is either a request or a response. A server listens on a connection for a request, parses each message received, interprets the message semantics in relation to the identified request target, and responds to that request with one or more response messages. A client constructs request messages to communicate specific intentions, examines received responses to see if the intentions were carried out, and determines how to interpret the results.
A web browser may be the client, and an application on a computer that hosts a web site may be the server.
Example: A client (browser) submits an HTTP request to the server; then the server returns a response to the client. The response contains status information about the request and may also contain the requested content.
Two HTTP Request Methods: GET and POST
Two commonly used methods for a request-response between a client and server are: GET and POST.
- GET – Requests data from a specified resource
- POST – Submits data to be processed to a specified resource
GET
The GET method requests transfer of a current selected representation for the target resource. GET is the primary mechanism of information retrieval and the focus of almost all performance optimizations. Hence, when people speak of retrieving some identifiable information via HTTP, they are generally referring to making a GET request.
The GET Method
Note that the query string (name/value pairs) is sent in the URL of a GET request:
/test/demo_form.php?name1=value1&name2=value2
Some other notes on GET requests:
- GET requests can be cached
- GET requests remain in the browser history
- GET requests can be bookmarked
- GET requests should never be used when dealing with sensitive data
- GET requests have length restrictions
- GET requests should be used only to retrieve data
ESP8266 GET Example Code
Make changes in wifi settings, SSID and password of your wifi network and change server ip. Also change GET request data as per your server requirements.
/* * HTTP Client GET Request * Copyright (c) 2018, circuits4you.com * All rights reserved. * https://circuits4you.com * Connects to WiFi HotSpot. */ #include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WebServer.h> #include <ESP8266HTTPClient.h> /* Set these to your desired credentials. */ const char *ssid = "circuits4you.com"; //ENTER YOUR WIFI SETTINGS const char *password = "yourPassword"; //Web/Server address to read/write from const char *host = "192.168.43.128"; //https://circuits4you.com website or IP address of server //======================================================================= // Power on setup //======================================================================= void setup() { delay(1000); Serial.begin(115200); WiFi.mode(WIFI_OFF); //Prevents reconnection issue (taking too long to connect) delay(1000); WiFi.mode(WIFI_STA); //This line hides the viewing of ESP as wifi hotspot WiFi.begin(ssid, password); //Connect to your WiFi router Serial.println(""); Serial.print("Connecting"); // 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 } //======================================================================= // Main Program Loop //======================================================================= void loop() { HTTPClient http; //Declare object of class HTTPClient String ADCData, station, getData, Link; int adcvalue=analogRead(A0); //Read Analog value of LDR ADCData = String(adcvalue); //String to interger conversion station = "B"; //GET Data getData = "?status=" + ADCData + "&station=" + station ; //Note "?" added at front Link = "http://192.168.43.128/c4yforum/getdemo.php" + getData; http.begin(Link); //Specify request destination int httpCode = http.GET(); //Send the request String payload = http.getString(); //Get the response payload Serial.println(httpCode); //Print HTTP return code Serial.println(payload); //Print request response payload http.end(); //Close connection delay(5000); //GET Data at every 5 seconds } //=======================================================================
Upload the code and open serial monitor, in case of any problem it will show errors.
Server side programs
Server side program consists of three parts 1. Database creation 2. Data logging and 3. Display logged data. To run this codes you need WAMP or LAMP installed (apache2, mySql and PHP)
Database creation PHP Code i.e. install.php
Enter your mySQL usename and password in code.
install.php
This program will create database and tables required for our demo application. This is run once code.
<?php //Create Data base if not exists $servername = "localhost"; $username = "root"; $password = "root"; // Create connection $conn = new mysqli($servername, $username, $password); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Create database $sql = "CREATE DATABASE espdemo"; if ($conn->query($sql) === TRUE) { echo "Database created successfully"; } else { echo "Error creating database: " . $conn->error; } $conn->close(); echo "<br>"; //Connect to database and create table $servername = "localhost"; $username = "root"; $password = "root"; $dbname = "espdemo"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } //Sr No, Station, Status(OK, NM, WM, ACK) Date, Time //1 A NM 12-5-18 12:15:00 am // sql to create table $sql = "CREATE TABLE logs ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, station VARCHAR(30), status VARCHAR(30), remark VARCHAR(50), `Date` DATE NULL, `Time` TIME NULL, `TimeStamp` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP )"; if ($conn->query($sql) === TRUE) { echo "Table logs created successfully"; } else { echo "Error creating table: " . $conn->error; } $conn->close(); ?>
Data logging PHP Code which handles GET request
getdemo.php
This is responsible for storing data into database. it will give only OK or Errors.
<?php //Creates new record as per request //Connect to database $servername = "localhost"; $username = "root"; $password = "root"; $dbname = "espdemo"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Database Connection failed: " . $conn->connect_error); } //Get current date and time date_default_timezone_set('Asia/Kolkata'); $d = date("Y-m-d"); //echo " Date:".$d."<BR>"; $t = date("H:i:s"); if(!empty($_GET['status']) && !empty($_GET['station'])) { $status = $_GET['status']; $station = $_GET['station']; $sql = "INSERT INTO logs (station, status, Date, Time) VALUES ('".$station."', '".$status."', '".$d."', '".$t."')"; if ($conn->query($sql) === TRUE) { echo "OK"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } } $conn->close(); ?>
Display logged data
view.php File
This will show logged data in web browser
<!DOCTYPE html> <html> <head> <meta http-equiv="refresh" content="5"> </head> <body> <style> #c4ytable { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; border-collapse: collapse; width: 100%; } #c4ytable td, #c4ytable th { border: 1px solid #ddd; padding: 8px; } #c4ytable tr:nth-child(even){background-color: #f2f2f2;} #c4ytable tr:hover {background-color: #ddd;} #c4ytable th { padding-top: 12px; padding-bottom: 12px; text-align: left; background-color: #00A8A9; color: white; } </style> <?php //Connect to database and create table $servername = "localhost"; $username = "root"; $password = "root"; $dbname = "espdemo"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Database Connection failed: " . $conn->connect_error); echo "<a href='install.php'>If first time running click here to install database</a>"; } ?> <div id="cards" class="cards"> <?php $sql = "SELECT * FROM logs ORDER BY id DESC"; if ($result=mysqli_query($conn,$sql)) { // Fetch one and one row echo "<TABLE id='c4ytable'>"; echo "<TR><TH>Sr.No.</TH><TH>Station</TH><TH>ADC Value</TH><TH>Date</TH><TH>Time</TH></TR>"; while ($row=mysqli_fetch_row($result)) { echo "<TR>"; echo "<TD>".$row[0]."</TD>"; echo "<TD>".$row[1]."</TD>"; echo "<TD>".$row[2]."</TD>"; //echo "<TD>".$row[3]."</TD>"; echo "<TD>".$row[4]."</TD>"; echo "<TD>".$row[5]."</TD>"; echo "</TR>"; } echo "</TABLE>"; // Free result set mysqli_free_result($result); } mysqli_close($conn); ?> </body> </html>
Display of logged data
This way you can make your own cloud server for data logging and displaying it.
Hello Sir/Mam,
The Server side is clear Created a Table and View.php Refreshes Every Five Seconds.
The Esp8266 side also clear it craeted a ip using my network and reads a data but that data is not displayed in my view.php
Can u plz help me to sort this problem