GET request using ESP8266

Hi Everyone,

I have been trying to get this to work with my code however it doesn't seem to want to work.
Any ideas as to why?

I am basically trying to retireve data from my website/database.
I am using the GET request from the form that I have used to send data to my database.
I know the fields that are stated bellow are spelt correctly and in the correct character case.

I found this example here ESP8266 HTTP GET Request Example | Circuits4you.com

  Serial.println("recieve test bellow");

   String volume, gain, treble, bass, contour, getData, Link;
//  int adcvalue=analogRead(A0);  //Read Analog value of LDR
//  volume = String(volume); 
//  gain = String(gain); 
//  treble = String(treble); 
//  bass = String(bass); 
//  contour = String(contour); 
  //  station = "B";
 
  //GET Data
  getData = "?volume=" + volume + "&gain=" + gain + "&treble=" + treble + "&bass=" + bass + "&contour" + contour; ;  //Note "?" added at front
  Link = "http://192.168.0.5/pre-play/Save.php" + getData;
 
  http.begin(Link);     //Specify request destination
  Serial.println("test values from website");
  Serial.print(volume);
    Serial.print(gain);
      Serial.print(treble);
        Serial.print(bass);
          Serial.print(contour);
  Serial.println("");
  int httpCode = http.GET();

Kind Regards,
Ben

Any ideas as to why?

No, because you're hiding the important parts of the code from us! Post only complete code!

You are not receiving any data, you are sending it. A "GET" request is a method where a query is appended to the URL and a "POST" request is a method where the query is posted as a body to the request. You need to extract data below the last line in your friggin' snippet.

Hi Danois,

I have got a POST working which sends data to my database that works almost fine just need to make some tweaks to it.

As for Pylon this is the only code used for calling the data the rest is posting so from what I can gather isn’t related to it but if you need to see it then I have posted all my code bellow.

How would I go about fixing this as I have looked online on how to do this and they all either don’t show you or they are using LED’s where I am using integers.
Is this the same method?

#include <ESP8266WiFi.h>
#include <WiFiClient.h> 
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

int Volume = 2;
int Gain = 2;
int Treble = 2;
int Bass = 2;
int Contour = 2;

const char* ssid = "VM082331-2G";   // Home Network
const char* password = "";

//const char* ssid = "BeniPhone";  // Hotspot
//const char* password = "gibsg888";

const char* host = "192.168.0.5"; // changes everytime you switch networks (Also Change http.begin to match this)

void setup(){
  delay(1000);
  pinMode(Volume, OUTPUT);
  pinMode(Gain, OUTPUT);
  pinMode(Treble, OUTPUT);
  pinMode(Bass, OUTPUT);
  pinMode(Contour, OUTPUT);
  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);
  Serial.println("");

  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
    Serial.print(".");
    delay(250);
  }
  Serial.println("");
  Serial.println("Connected to Network/SSID");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop(){
  HTTPClient http;    //Declare object of class HTTPClient
 
  String VolValueSend, volData;
  String GaiValueSend, gaiData;
  String TreValueSend, treData;
  String BasValueSend, basData;
  String ConValueSend, conData;
  
  int volvalue=analogRead(A0);
  int gaivalue=analogRead(A0);
  int trevalue=analogRead(A0);
  int basvalue=analogRead(A0);
  int convalue=analogRead(A0);//Read Analog value of LDR

  VolValueSend = String(volvalue);
  GaiValueSend = String(gaivalue);
  TreValueSend = String(trevalue);
  BasValueSend = String(basvalue);
  ConValueSend = String(convalue);   //String to interger conversion
 
  //Post Data /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  volData = "volvalue=" + VolValueSend;
  gaiData = "gaivalue=" + GaiValueSend;
  treData = "trevalue=" + TreValueSend;
  basData = "basvalue=" + BasValueSend;
  conData = "convalue=" + ConValueSend;
  
  http.begin("http://192.168.0.5/Pre-Play/InsertDB.php");              //Specify request destination
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");    //Specify content-type header
 
  int volCode = http.POST(volData);
    int gaiCode = http.POST(gaiData); 
      int treCode = http.POST(treData); 
        int basCode = http.POST(basData); 
          int conCode = http.POST(conData); //Send the request
  String payload = http.getString();    //Get the response payload

  Serial.println("Volume Value=" + volvalue);
  Serial.println(volCode);   //Print HTTP return code
  Serial.println(payload);    //Print request response payload
  Serial.println("Volume send Value=" + VolValueSend);

  Serial.println("Gain Value=" + gaivalue);
  Serial.println(gaiCode);   //Print HTTP return code
  Serial.println(payload);    //Print request response payload
  Serial.println("Gain send Value=" + GaiValueSend);

  Serial.println("Treble Value=" + trevalue);
  Serial.println(treCode);   //Print HTTP return code
  Serial.println(payload);    //Print request response payload
  Serial.println("Treble send Value=" + TreValueSend);

  Serial.println("Bass Value=" + basvalue);
  Serial.println(basCode);   //Print HTTP return code
  Serial.println(payload);    //Print request response payload
  Serial.println("Bass send Value=" + BasValueSend);

  Serial.println("Contour Value=" + convalue);
  Serial.println(conCode);   //Print HTTP return code
  Serial.println(payload);    //Print request response payload
  Serial.println("Contour send Value=" + ConValueSend);


  Serial.println("recieve test bellow");

   String volume, gain, treble, bass, contour, getData, Link;
//  int adcvalue=analogRead(A0);  //Read Analog value of LDR
//  volume = String(volume);  
//  gain = String(gain);  
//  treble = String(treble);  
//  bass = String(bass);  
//  contour = String(contour);  
  //  station = "B";
 
  //GET Data
  getData = "?volume=" + volume + "&gain=" + gain + "&treble=" + treble + "&bass=" + bass + "&contour" + contour; ;  //Note "?" added at front
  Link = "http://192.168.0.5/pre-play/Save.php" + getData;
  
  http.begin(Link);     //Specify request destination
  Serial.println("test values from website");
  Serial.print(volume);
    Serial.print(gain);
      Serial.print(treble);
        Serial.print(bass);
          Serial.print(contour);
  Serial.println("");
  int httpCode = http.GET();          
 
  http.end();  //Close connection

  delay(500);  //Here there is 4 seconds delay plus 1 second delay below, so Post Data at every 5 seconds
  digitalWrite(Volume, LOW);
  digitalWrite(Gain, LOW);
  digitalWrite(Treble, LOW);
  digitalWrite(Bass, LOW);
  digitalWrite(Contour, LOW);
  delay(500);
  digitalWrite(Volume, HIGH);
  digitalWrite(Gain, HIGH);
  digitalWrite(Treble, HIGH);  
  digitalWrite(Bass, HIGH);
  digitalWrite(Contour, HIGH);
}

Jeez.. I guess you need to change the password for you home network as the first thing..

Danois90:
Jeez.. I guess you need to change the password for you home network as the first thing..

hahaha only if you find me :wink: XD

any ideas on this anyways?

BenjaminoTzu:
any ideas on this anyways?

Are you able to do what you want using a web browser instead of the 8266?

In the example you've used, you missed a crucial part:

int httpCode = http.GET();

//Grab the response from the get request:
String response = http.getString();

http.end();  //Close connection

//Do something with the response:
Serial.println("Response from GET request:");
Serial.println(response);

You should also try to combine all your POST requests into one as you do with the GET request. If the GET request is about getting data from the database, it makes little sense to append the data to the query.

How would I go about fixing this as I have looked online on how to do this and they all either don't show you or they are using LED's where I am using integers.

You don't even read the response of the web server, how do you know that it didn't work?

zoomkat:
Are you able to do what you want using a web browser instead of the 8266?

I'm sorry I don't quite know what you mean. Do you mean pulling http Queries like this?

http://localhost/pre-play/Save.php?volume=123123&gain=232344&treble=11&bass=11&contour=1123
and pulling the data out of that?
If so that is what I am trying to do basically.

Danois90:
In the example you've used, you missed a crucial part:

int httpCode = http.GET();

//Grab the response from the get request:
String response = http.getString();

http.end();  //Close connection

//Do something with the response:
Serial.println("Response from GET request:");
Serial.println(response);




You should also try to combine all your POST requests into one as you do with the GET request. If the GET request is about getting data from the database, it makes little sense to append the data to the query.

I have tried this and I get nothing appearing in the serial monitor perhaps this is due to me using POST with them being different functions? I did try http.POST() however this either needs a library? or isn't a supported command from the error I got.

pylon:
You don't even read the response of the web server, how do you know that it didn't work?

Hi not sure as I am following tutorials on how to do it.
I am getting confused as this is my first time programming a node mcu.
All I basically want to do is store some data from the form that is submitted so I can use it with some potentiometers on an arduino.

Sorry I know I'm not the best at explaining don't really know how to explain these things.

POST and GET does the same thing but in different ways, so that is not the problem.. Is there a source to the PHP files InsertDB.php and Save.php - both sound like they are used to insert dat to a database and not read out any data..

BenjaminoTzu:
hahaha only if you find me :wink: XD

Someone (like Google, Facebook or evil alike) will, change your password and do not post it again, EVER!!

Danois90:
POST and GET does the same thing but in different ways, so that is not the problem… Is there a source to the PHP files InsertDB.php and Save.php - both sound like they are used to insert dat to a database and not read out any data…

This is the PhP.
I haven’t used this for a project in while so looks kind of messy.
The insertDB adds what is being sent from the node to the database.

This is one way I have tried it.
This returned nothing.

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";	
    $dbname = "Pre-Play";
		$conn = mysqli_connect($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Database Connection failed: " . $conn->connect_error);
    }
    if(!empty($_POST['volvalue'] && $_POST['gaivalue']))
    {
		$volvalue = $_POST['volvalue'];
        $gaivalue = $_POST['gaivalue'];
	    $sql = "INSERT INTO retrieve (volume,gain)VALUES ('".$volvalue."','".$gaivalue."')"; 
		if ($conn->query($sql) === TRUE) {
		    echo "OK";
		} else {
		    echo "Error: " . $sql . "
" . $conn->error;
		}
	}
	$conn->close();
?>

This is second way which added data into the volume column but no others.

 <?php
    $servername = "localhost";
    $username = "root";
    $password = "";	
    $dbname = "Pre-Play";
		$conn = mysqli_connect($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Database Connection failed: " . $conn->connect_error);
    }
    if(!empty($_POST['volvalue']))
    {
		$volvalue = $_POST['volvalue'];
	    $sql = "INSERT INTO retrieve (volume,gain)VALUES ('".$volvalue."')"; 
		if ($conn->query($sql) === TRUE) {
		    echo "OK";
		} else {
		    echo "Error: " . $sql . "
" . $conn->error;
		}
	}
    if(!empty($_POST['gaivalue']))
    {
		$gaivalue = $_POST['gaivalue'];
	    $sql = "INSERT INTO retrieve (gain)VALUES ('".$gaivalue."')"; 
		if ($conn->query($sql) === TRUE) {
		    echo "OK";
		} else {
		    echo "Error: " . $sql . "
" . $conn->error;
		}
	}
    if(!empty($_POST['trevalue']))
    {
		$trevalue = $_POST['trevalue'];
	    $sql = "INSERT INTO retrieve (treble)VALUES ('".$trevalue."')"; 
		if ($conn->query($sql) === TRUE) {
		    echo "OK";
		} else {
		    echo "Error: " . $sql . "
" . $conn->error;
		}
	}
    if(!empty($_POST['basvalue']))
    {
		$basvalue = $_POST['basvalue'];
	    $sql = "INSERT INTO retrieve (bass)VALUES ('".$basvalue."')"; 
		if ($conn->query($sql) === TRUE) {
		    echo "OK";
		} else {
		    echo "Error: " . $sql . "
" . $conn->error;
		}
	}
    if(!empty($_POST['convalue']))
    {
		$convalue = $_POST['convalue'];
	    $sql = "INSERT INTO retrieve (contour)VALUES ('".$value."')"; 
		if ($conn->query($sql) === TRUE) {
		    echo "OK";
		} else {
		    echo "Error: " . $sql . "
" . $conn->error;
		}
	}

	$conn->close();
?>

What Save does is basically save the settings in case a user wants to revert back to them later so stores them in the database.
This saves info to the database fine.

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";	
    $dbname = "Pre-Play";
		$conn = mysqli_connect($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Database Connection failed: " . $conn->connect_error);
    }

//$request = $_GET[volume]
//
//echo $request;

	    $sql = "INSERT INTO send (volume, gain, treble, bass, contour) VALUES ('$_GET[volume]','$_GET[gain]','$_GET[treble]','$_GET[bass]','$_GET[contour]')"; 
		if ($conn->query($sql) === TRUE) {
		    echo "OK";
		} else {
		    echo "Error: " . $sql . "
" . $conn->error;
		}
?>

Can you see anything wrong here.
I’ve sent it through some Php checkers and although it looks pretty messy they came back saying that they’re clean of grammatical errors.

I'm not really a PHP guy.. InsertDB only stores 2 values (volume & gain) but you are performing 5 POST request with each its own value - you should post all the values you need in one combined request. By posting each value one by one, you will cause 5 rows to be inserted to the database and you only need one row with all values.

Since you have already stored the values in table "retrieve" I cannot see why you would also store them in table "send" - that makes no sense. Since no data is send from the "Send" script, you will not be able to retreive them on the ESP.

So it's a mishmash that needs to be thought through a bit more.. :wink:

Hi,

Yeah theres only two in there at the moment but there were 5 in there originally i've just been trying to get to the bottom of the code.

as for submitting them all at once it constantly failed and wouldn't upload any data that's why I have tried doing it one by one.

The table "recieve" gets data from the nodemcu and the table "send" sends data to the node that's why there are two.

BenjaminoTzu:
The table "recieve" gets data from the nodemcu and the table "send" sends data to the node that's why there are two.

Har to see when you use a "INSERT" query and not a "SELECT" query. However, the "Send" script needs to output the values from the database in order for the MCU to receive them. The arguments used to the script will not be modified during the request and thus they are useless in the context..

Danois90:
Har to see when you use a "INSERT" query and not a "SELECT" query. However, the "Send" script needs to output the values from the database in order for the MCU to receive them. The arguments used to the script will not be modified during the request and thus they are useless in the context..

The Values from send are initially stored in the URL and that's what I have been trying to pull down. Is it not possible to pull it down like this?

If I'm being honest it is still quite new to me with connecting the node to Websites. So a lot of this goes right over my head.

Any idea where I can look to try sort this out?

Thanks for helping me,
Ben

As I understand you, you want to store some values from the ESP to a server and also be able to change some settings in the ESP based on values from the server. That should be pretty straight forward, but before you can create a client, you need the server to work properly.

I would create a table with the following structure (untested SQL):

CREATE TABLE audio_settings (
  id BIGINT UNSIGNED AUTO_INCREMENT,
  volume SMALLINT UNSIGNED DEFAULT 0,
  treble SMALLINT UNSIGNED DEFAULT 0,
  bass SMALLINT UNSIGNED DEFAULT 0,
  upload BOOL DEFAULT 1,
  time DATETIME DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id)
)

This will make it possible to both store uploads (from ESP) and downloads (to ESP) in the same table. Next you need to create a PHP script which has the following operation (pseudocode):

//Get values from query string (GET) or post data (POST)
m_volume = integer(query("volume"))
m_treble = integer(query("treble"))
m_bass = integer(query("bass"))

if (volume>0 OR treble>0 OR bass>0)
{
  //If values are send, store them to the database
  database.execute(
    INSERT INTO audio_settings (volume, treble, bass)
    VALUES (m_volume, m_treble, m_bass)
  )   
}

//Check if the client wants new settings?
m_last_value_id = integer(query("last_value_id"))

if (m_last_value_id > 0)
{
  //Get values newer than the posted ID:
  database.open(SELECT * FROM audio_settings WHERE upload=false AND id>m_last_value_id ORDER BY id DESC)
  if (database.has_rows())
  {
    //If available, send to client
    println("id=" + database[id])
    println("volume=" + database[volume])
    println("treble=" + database[treble])
    println("bass=" + database[bass])
    println("time=" + database[time])
  }
  database.close()
}

By doing it this way, one table in the database and one script on the server will perform all the required operations needed by the client.

I have been trying to get your suggested code working however I can’t seem to get it to work or format it correctly.

Your SQL works brill just one tweak as I had to rename BOOL to BIT which works just like Boolean in SQL.

I have also reworked my code for a good few hours today and I believe the issue is something to do with the HTTP POST from the Arduino. I found that by removing the POST[volData] that it would then upload the POST[gaiData] instead.

However since this development I have changed my code some more and broken it again. From the serial Monitor I get HTTP Request code 200 for all the values sent to the webpage however when I call the POST attribute in the PhP it doesn’t input anything. Any Ideas why this is? I know the database is set up right as everything is set to integers. But not 100% sure about the Arduino or PhP side.

I have also made the code to run not just of the analog read input but random strings of numbers too.

Any Ideas on this?

Php Code

<?php
error_reporting(E_ALL);
    $servername = "localhost";
    $username = "root";
    $password = "";	
    $dbname = "Pre-Play";
		$conn = mysqli_connect($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Database Connection failed: " . $conn->connect_error);
    }
 
if(!empty($_POST))
    {
    $volume = $_POST['VolValueSend'];
    $gain = $_POST['gaiCode'];
    $treble = $_POST['treCode'];
    $bass = $_POST['basCode'];
    $contour = $_POST['conCode'];
    echo "Post Results";
echo $volume;
echo $_POST['VolValueSend'];
	    $sql = "INSERT INTO retrieve (volume)VALUES ('".$volume."')"; 
		if ($conn->query($sql) === TRUE) {
		    echo "OK";
		} else {
		    echo "Error: " . $sql . "
" . $conn->error;
		}
	}
//	    $sql = "INSERT INTO retrieve (volume,gain,treble,bass,contour)VALUES ('".$volume."','".$gain."','".$treble."','".$bass."','".$contour."')"; 
//		if ($conn->query($sql) === TRUE) {
//		    echo "OK";
//		} else {
//		    echo "Error: " . $sql . "
" . $conn->error;
//		}
//	}


	$conn->close();
?>

<h1>hello</h1>

Node Code

#include <ESP8266WiFi.h>
#include <WiFiClient.h> 
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include<SoftwareSerial.h>

SoftwareSerial s(3,1);

int data = 1257654;

int Volume = 2;
int Gain = 2;
int Treble = 2;
int Bass = 2;
int Contour = 2;

const char* ssid = "VM082331-2G";   // Home Network
const char* password = "franco123";

//const char* ssid = "BeniPhone";  // Hotspot
//const char* password = "gibsg888";

const char* host = "192.168.0.5"; // changes everytime you switch networks (Also Change http.begin to match this)

void setup(){
  s.begin(9600);
  delay(1000);
  pinMode(Volume, OUTPUT);
  pinMode(Gain, OUTPUT);
  pinMode(Treble, OUTPUT);
  pinMode(Bass, OUTPUT);
  pinMode(Contour, OUTPUT);
  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);
  Serial.println("");

  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
    Serial.print(".");
    delay(250);
  }
  Serial.println("");
  Serial.println("Connected to Network/SSID");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop(){
  Serial.write(data);
  
  HTTPClient http;    //Declare object of class HTTPClient
 
  String VolValueSend, volData;
  String GaiValueSend, gaiData;
  String TreValueSend, treData;
  String BasValueSend, basData;
  String ConValueSend, conData;

  int vol = 1235;
  int analog = analogRead(A0);
  int tre = 54545;
  int bas = 1111;
  int con = 64;
  
  int m_volume=vol;
  int m_gain=analog;
  int m_treble=tre;
  int m_bass=bas;
  int m_contour=con;//Read Analog value of LDR

  VolValueSend = String(m_volume);
  GaiValueSend = String(m_gain);
  TreValueSend = String(m_treble);
  BasValueSend = String(m_bass);
  ConValueSend = String(m_contour);   //String to interger conversion
 
  //Post Data /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//  volData = VolValueSend;
//  gaiData = GaiValueSend;
//  treData = TreValueSend;
//  basData = BasValueSend;
//  conData = ConValueSend;
  
  http.begin("http://192.168.0.5/Pre-Play/InsertDB.php");              //Specify request destination
  http.addHeader("Content-Type", "application/x-www-form-urlencoded");    //Specify content-type header
 
  int volCode = http.POST(VolValueSend);
  int gaiCode = http.POST(gaiData); 
  int treCode = http.POST(treData); 
  int basCode = http.POST(basData); 
  int conCode = http.POST(conData); //Send the request
  String payload = http.getString();    //Get the response payload

  Serial.println(payload); 

// recieve data
  Serial.println("Volume Value=" + volData);
  Serial.println(volCode);   //Print HTTP return code

  Serial.println("Gain Value=" + gaiData);
  Serial.println(gaiCode);   //Print HTTP return code

  Serial.println("Treble Value=" + m_treble);
  Serial.println(treCode);   //Print HTTP return code

  Serial.println("Bass Value=" + m_bass);
  Serial.println(basCode);   //Print HTTP return code

  Serial.println("Contour Value=" + m_contour);
  Serial.println(conCode);   //Print HTTP return code  

  String response = http.getString();
  http.end();  //Close connection

  delay(500);  //Here there is 4 seconds delay plus 1 second delay below, so Post Data at every 5 seconds
  digitalWrite(Volume, LOW);
  digitalWrite(Gain, LOW);
  digitalWrite(Treble, LOW);
  digitalWrite(Bass, LOW);
  digitalWrite(Contour, LOW);
  delay(500);
  digitalWrite(Volume, HIGH);
  digitalWrite(Gain, HIGH);
  digitalWrite(Treble, HIGH);  
  digitalWrite(Bass, HIGH);
  digitalWrite(Contour, HIGH);
}

Thanks Again for looking :slight_smile:

You are still performing 5 (malformed) POST requests, where you only need one working request. It seems that you did not read post #2, POST and GET requests are doing the same thing - but in different ways. You are also having multiple variables for the same value (eg. "vol" and "m_volume") which is not necessary.