Webserver POST data reading error

Hello experts,

I am using ESP8266 01.
I am working on a project that uses 'ESP8266WebServer.h' & I had served an HTML file using this so when I opened this file, it sent current date & time data to the ESP using HTTP POST & it should Print that data on the serial monitor.

But the issue is it doesn't print the data! It is printing blank values.

00:40:31.593 -> Current fetched time n date: //-::

The code related to the output is:

 webServer.on("/dtTmUpdateRTC", HTTP_POST, []() {
    String yr0 = webServer.arg("yr0");
    String mnt0 = webServer.arg("mnt0");
    String dt0 = webServer.arg("dt0");
    String hr0 = webServer.arg("hr0");
    String min0 = webServer.arg("min0");
    String sec0 = webServer.arg("sec0");


    Serial.println("Current fetched time n date: " + yr0 + "/" + mnt0 + "/" + dt0 + "-" + hr0 + ":" + min0 + ":" + sec0);

    webServer.send(200, "text/plain", "Date n Time Received!");
  });

The complete code:

#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <Preferences.h>
#include "html_strings.h"

const byte DNS_PORT = 53;
IPAddress apIP(192, 168, 0, 8);
DNSServer dnsServer;
ESP8266WebServer webServer(80);
Preferences preferences;





void handleAddEventPage() {
  webServer.send(200, "text/html", add_editEventHtml);
}





void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
  WiFi.softAP("Wifi", "Password");

  dnsServer.start(DNS_PORT, "*", apIP);

  webServer.onNotFound([]() {
    webServer.send(200, "text/html", homePageHtml);
  });

  webServer.on("/add_event", HTTP_GET, handleAddEventPage);  // Define the endpoint for the Add Event page


  webServer.on("/dtTmUpdateRTC", HTTP_POST, []() {
    String yr0 = webServer.arg("yr0");
    String mnt0 = webServer.arg("mnt0");
    String dt0 = webServer.arg("dt0");
    String hr0 = webServer.arg("hr0");
    String min0 = webServer.arg("min0");
    String sec0 = webServer.arg("sec0");


    Serial.println("Current fetched time n date: " + yr0 + "/" + mnt0 + "/" + dt0 + "-" + hr0 + ":" + min0 + ":" + sec0);

    webServer.send(200, "text/plain", "Date n Time Received!");
  });


  webServer.on("/manBtnHandler", HTTP_POST, []() {
    String switchStateRelay = webServer.arg("switchStateRelay");

    webServer.send(200, "text/plain", "Btn data recieved");

    Serial.println("Button State:" + switchStateRelay);
  });


  webServer.begin();
}

void loop() {
  dnsServer.processNextRequest();
  webServer.handleClient();

}

.
html_strings.h:

String homePageHtml = R"(
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Toggle Button</title>
    <style>
        .container {
            display: inline-block;
            padding: 10px;
            background-color: #707070;
            /* Set your desired background color */
            border-radius: 10px;
            /* Set your desired border radius */
            margin: 20px;
        }

        /* Style for the toggle button */
        .toggle {
            display: inline-block;
            width: 60px;
            height: 34px;
            position: relative;
        }

        /* Style for the slider */
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 34px;
        }

        /* Style for the circle */
        .slider:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        /* Style for the toggle button when active */
        input:checked+.slider {
            background-color: #2196F3;
        }

        /* Style for the circle when active */
        input:checked+.slider:before {
            transform: translateX(26px);
        }
    </style>
</head>

<body>



    <!-- Input checkbox element that acts as the toggle -->
    <div class="container">
        <h2>Switch</h2>

        <label class="toggle">
    <input type="checkbox" id="toggleButton" onchange='togglePost()' style="margin-left: 10px;">
    <span class="slider"></span>
</label>
    </div>

    <script>



        // Variable to hold the initial state of the toggle button
        var initialToggleState = 1;

        // Function to set the initial state of the toggle button
        window.onload = function () {
            var checkbox = document.getElementById('toggleButton');
            checkbox.checked = initialToggleState;




            //HTTP POST date & time
            // Get the current date and time
            var currentDate = new Date();

            // Extract the components of the current date and time
            var yr = currentDate.getFullYear();
            var mnt = currentDate.getMonth() + 1; // Months are zero-based
            var dt = currentDate.getDate();
            var hr = currentDate.getHours();
            var min = currentDate.getMinutes();
            var sec = currentDate.getSeconds();

            // Format the date and time as a string (adjust format as needed)
            var formattedTime = yr + '-' + pad(mnt) + '-' + pad(dt) + ' ' + pad(hr) + ':' + pad(min) + ':' + pad(sec);

            console.log(formattedTime)

            // Send the current local time details via HTTP POST
            fetch('dtTmUpdateRTC', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    // Add any additional headers if needed
                },
                body: JSON.stringify({
                    yr0: yr,
                    mnt0: mnt,
                    dt0: dt,
                    hr0: hr,
                    min0: min,
                    sec0: sec,
                })
            })
        }

        function togglePost() {

            // Get the checkbox element
            var checkbox = document.getElementById('toggleButton');

            // Check if the checkbox is checked
            if (checkbox.checked) {
                // Perform HTTP POST request in the background
                fetch('manBtnHandler', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        // Add any additional headers if needed
                    },
                    body: JSON.stringify({
                        switchStateRelay: 1 // Set switchState to 1
                        // Add any additional data you want to send in the POST request body
                    })
                })
            } else {
                // Perform HTTP POST request in the background
                fetch('manBtnHandler', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        // Add any additional headers if needed
                    },
                    body: JSON.stringify({
                        switchStateRelay: 0 // Set switchState to 1
                        // Add any additional data you want to send in the POST request body
                    })
                })
            }
        }


        function pad(number) {
        return (number < 10 ? '0' : '') + number;
    }
    </script>

</body>

</html>
  )";





String add_editEventHtml = R"(
XYZ
)";

Please help to find the reason behind this.

Thanks & Regards!!

--SRJ

You should check to see what you are receiving. After a brief google, it appears that Webserver may be a bit finicky

This issur is occured only when I am using fetch in js for posting data.

When I am posting the data by form submit, it is working...

Should I do any changes in the code?

Is there any other library available which can help me in my desired behaviour?

Try sending to http://httpbin.org/anything/ with both a form and fetch to see if there are any differences in how a server sees the request. You can add your URL path: /anything/your_path_here?and=some&more=params

you are not interested in using HTTP GET ?

Nope!!

But if it can help me then I will try it too...

okay my web script would look like this

String homePageHtml = R"(

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Toggle Button</title>
    <style>
        .container {
            display: inline-block;
            padding: 10px;
            background-color: #707070;
            /* Set your desired background color */
            border-radius: 10px;
            /* Set your desired border radius */
            margin: 20px;
        }

        /* Style for the toggle button */
        .toggle {
            display: inline-block;
            width: 60px;
            height: 34px;
            position: relative;
        }

        /* Style for the slider */
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 34px;
        }

        /* Style for the circle */
        .slider:before {
            position: absolute;
            content: "";
            height: 26px;
            width: 26px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        /* Style for the toggle button when active */
        input:checked+.slider {
            background-color: #2196F3;
        }

        /* Style for the circle when active */
        input:checked+.slider:before {
            transform: translateX(26px);
        }
    </style>
</head>

<body>

<br><br>



    <!-- Input checkbox element that acts as the toggle -->
    <div class="container">
        <h2>Switch</h2>

        <label class="toggle">
    <input type="checkbox" id="toggleButton" onchange='togglePost()' style="margin-left: 10px;">
    <span class="slider"></span>
</label>
    </div>
	
	<br><br>

    <script>

        // Variable to hold the initial state of the toggle button
        var initialToggleState = 1;

        // Function to set the initial state of the toggle button
        window.onload = function () {
            var checkbox = document.getElementById('toggleButton');
            checkbox.checked = initialToggleState;




            //HTTP POST date & time
            // Get the current date and time
            var currentDate = new Date();

            // Extract the components of the current date and time
            var yr = currentDate.getFullYear();
            var mnt = currentDate.getMonth() + 1; // Months are zero-based
            var dt = currentDate.getDate();
            var hr = currentDate.getHours();
            var min = currentDate.getMinutes();
            var sec = currentDate.getSeconds();

            // Format the date and time as a string (adjust format as needed)
            var formattedTime = yr + '/' + pad(mnt) + '/' + pad(dt) + '-' + pad(hr) + ':' + pad(min) + ':' + pad(sec);

          //  console.log(formattedTime);
			
			sendData('dtTmUpdateRTC?formatted_time='+formattedTime,function(mm) {
                              alert(mm); 
                             });
        }

        function togglePost() {
            // Get the checkbox element
            var checkbox = document.getElementById('toggleButton');

            // Check if the checkbox is checked
            if (checkbox.checked) {
                
				sendData('manBtnHandler?switchStateRelay=1',function(mm) {
                              alert(mm); 
                             });
				
            } else {
               sendData('manBtnHandler?switchStateRelay=0',function(mm) {
                              alert(mm); 
                             });
            }
        }  // end


        function pad(number) {
        return (number < 10 ? '0' : '') + number;
    }  // end
	
	function sendData ( url,gotResp ) { 
                            console.log(url);	
                            var xhttp = new XMLHttpRequest();
                            xhttp.onreadystatechange = function() {
                            if (this.readyState == 4 && this.status == 200) {                        
                            gotResp( this.responseText );                           
                            }
                            };
                            xhttp.open('GET', url , true);
                            xhttp.send();
                            }   // end function
							
							
    </script>

</body>

</html>

  )";


and on the backend I'd handle the get RTC request like this

webServer.on("/dtTmUpdateRTC", dtTmUpdateRTCHandler);

then define my function as

void dtTmUpdateRTCHandler() {
       String formatted_time = server.arg("formatted_time");
       Serial.println("time: " + formatted_time);
       webServer.send(200, "text/plain", "Got The Time");
}  // end

This solved my problem!!

My Output:

17:24:04.176 -> time: 2024/04/09-17:24:04

Thanks for the code.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.