ESP8266 (NodeMCU) post request data to website

In this example we learn how to send post 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 GET 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

POST

The POST method requests that the target resource process the representation enclosed in the request according to the resource’s own specific semantics. For example, POST is used for the following functions (among others):

  1. Providing a block of data, such as the fields entered into an HTML form, to a data-handling process;
  2. Posting a message to a bulletin board, newsgroup, mailing list, blog, or similar group of articles;
  3. Creating a new resource that has yet to be identified by the origin server; and
  4. Appending data to a resource’s existing representation(s).

An origin server indicates response semantics by choosing an appropriate status code depending on the result of processing the POST request; almost all of the status codes defined by this specification might be received in a response to POST (the exceptions being 206 (Partial Content), 304 (Not Modified), and 416 (Range Not Satisfiable)).

The POST Method

Note that the query string (name/value pairs) is sent in the HTTP message body of a POST request:

POST / HTTP/1.1
Host: foo.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 13

say=Hi&to=Mom

Some other notes on POST requests:

  • POST requests are never cached
  • POST requests do not remain in the browser history
  • POST requests cannot be bookmarked
  • POST requests have no restrictions on data length

ESP8266 POST Example Code

Make changes in wifi settings, SSID and password of your wifi network and change server ip. Also change POST request data as per your server requirements.

/*
 * HTTP Client POST 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, postData;
  int adcvalue=analogRead(A0);  //Read Analog value of LDR
  ADCData = String(adcvalue);   //String to interger conversion
  station = "A";

  //Post Data
  postData = "status=" + ADCData + "&station=" + station ;
  
  http.begin("http://192.168.43.128/c4yforum/postdemo.php");              //Specify request destination
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");    //Specify content-type header

  int httpCode = http.POST(postData);   //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);  //Post 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 POST request

postdemo.php file

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($_POST['status']) && !empty($_POST['station']))
    {
    	$status = $_POST['status'];
    	$station = $_POST['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.

How to make GET request ? explained here

11 thoughts on “ESP8266 (NodeMCU) post request data to website

  1. Hello I’m getting an error and error code is 403 I tried to solve it but I can’t found out how can u pls help me?my code and output of my code below.Btw my internet connection OK. I only change the http.begin such as:

    Change of code:

    postData = “status=” + ADCData + “&station=” + station ;
    http.begin(“http://192.168.2.24/test2/postdemo.php”);
    http.addHeader(“Content-Type”, “application/x-www-form-urlencoded”);

    OUTPUT :
    403

    403 Forbidden

    Forbidden
    You don’t have permission to access /test2/postdemo.php
    on this server.

    Apache/2.4.37 (Win64) PHP/7.2.14 Server at 192.168.2.24 Port 80

  2. When I run my post data sketch and the MCU submiuts the post reequest, the target PHP script does not execute. The HTTP return code is is 200 and the Request response payload is tge text of the target php script ( the same as if i had browsed to the script).
    I have set the permissions to 777. What am I doing wrong?

  3. I have already tried this tutorial and GET tutorial too. It worked, but when i put the php files on hosting server, it didnt work. I already change the “host” address in the sketch and already try to open the web through a web browser (which can be opened) but the data that should be post by nodemcu did not get there (it is not like when i still use the localhost server). Could you help me to solve this?
    Thank you

    1. Most common problem is HTTPS Secured server See this tutorial
      https://circuits4you.com/2019/01/10/esp8266-nodemcu-https-secured-get-request/

      There are few reasons for that
      1. Your ESP is not getting internet connection.
      2. Linux server is case SenSiTive.
      3. Check http and https of your website
      4. Check GET request sent through browser is working properly .
      5. Also check response from server, on serial monitor.
      6. Check Database is created properly.

          1. Thank you for answer.I tried to reach localhost.should i specify to port i don’t know anything about it.
            http.begin(“http://192.168.2.24/test2/postdemo.php”);

  4. This a really good tutorial, well done. I am implementing a small project and i would like to ask how i could modify your tutorial. I have a server running LAMP (Linux, Apache, Mysql, Php7) and i need it to keep track on its database the value of 2 sensors.
    An ESP8266 nodemcu needs to have 2 magnetic door switches (named Door_A & Door_B). Once one of them change its state then send an update to the MYSQL, instead of polling it every x secs. Is there any way that i could implement that please?

Leave a Reply