I would like to control a relay using Wemos D! R1 via a website from anywhere. I managed to control it using local web server and now would like to step it up further.
I'm using the following code which connects to this website and retrieve data as JSON perfectly.
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
const char* ssid = "SSID";
const char* password = "PASS";
void setup () {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
}
void loop() {
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
Serial.println("");
HTTPClient http; //Declare an object of class HTTPClient
http.begin("http://jsonplaceholder.typicode.com/users/1"); //Specify request destination
int httpCode = http.GET(); //Send the request
if (httpCode > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
Serial.println(""); // Empty Line
Serial.println(payload); //Print the response payload
//////////////// Json code
StaticJsonDocument<2000> doc;
DeserializationError error = deserializeJson(doc, payload);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
return;
}
const char* sensor = doc["name"];
const char* username = doc["username"];
const char* email = doc["email"];
const char* address = doc["address"];
Serial.println(sensor);
Serial.println(username);
Serial.println(email);
Serial.println(address);
//////////////// End of Json Code
http.end(); //Close connection
while ( 0 < 1 ){ delay(10000); } // to break the loop
}
}
delay(10); //Send a request every 30 seconds
}
I made a web page that makes AJAX call to a PHP file to retrieve data from MYSQL DB, but when I run it, the monitor keeps printing empty lines forever although connected successfully to my WIFI.
$(document).ready(function(){
$.ajax({
url: "test.php",
type: 'GET',
dataType: 'json', // added data type
data: ({mobile: 'hi'}),
success: function(res) {
console.log(res);
}
});
});
The result I'm getting from AJAX is (which you can check visiting this link:
{"status":"ON"}
I'm using the following code on php file:
<?php
header('Content-type: application/json');
require 'functions.php';
header("Access-Control-Allow-Origin: *");
$catrecord = mysqli_query($link,"SELECT * FROM `ard`");
while($catinfo = mysqli_fetch_array($catrecord, MYSQLI_ASSOC)){ $Cat = $catinfo['status']; }
$responseArray = array('status' => $Cat );
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
} else {
echo $responseArray['status'];
}
?>