บทความนี้ เราจะทำการนำค่าจาก อุปกรณ์ IoT มาแสดงผลแบบ Real-time บนหน้าบทความของ Joomla กัน จะทำให้เราสามารถดูค่าจากตัว Sensor ต่างๆได้ง่ายขึ้น โดยใช้การดึงข้อมูลจาก API ที่เป็นรูปแบบข้อมูล JSON ร่วมกับ AJAX Script วิธีการนี้จะทำให้สามารถอัพเดตข้อมูลบนหน้าเพจได้โดยตรง โดยไม่ต้องใช้ทั้งการ Refresh page และ iframe
AJAX Asynchronouse Javascript Code:
<script type="application/javascript">
setInterval(loadJSON,5000);
function loadJSON()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// Parse the JSON data structure contained in xmlhttp.responseText using the JSON.parse function.
var JSONObject = JSON.parse(xmlhttp.responseText);
// The JSONObject variable now contains the data structure and can be accessed as JSONObject.firstName and
// JSONObject.lastName. Assign the object members to the DOM elements FirstName and LastName so that they get
// displayed on the page
document.getElementById("Temperature").innerHTML = JSONObject.temperature + "°C";
document.getElementById("Humidity").innerHTML = JSONObject.humidity + "%RH";
document.getElementById("Voltage").innerHTML = JSONObject.voltage + "V";
document.getElementById("Current").innerHTML = JSONObject.current + "A";
document.getElementById("Power").innerHTML = JSONObject.power + "W";
document.getElementById("Light").innerHTML = JSONObject.light + "Lux";
}
}
xmlhttp.open("GET","https://nodered.elec2rak.com/aht21-001-json",true);
xmlhttp.send();
}
</script>
Live & Real-time data from ESP-01S + AHT21 WiFi MQTT Temperature and Humidity Sensor
Sunlight: Sunlight Lux
Temperature: Temperature °C
Humidity: Humidity %RH
Live & Real-time data from ESP-01S + PZEM-004T WiFi MQTT Smart Energy Meter
Voltage: Voltage V
Current: Current A
Power: Power W
Energy Today: EnergyToday kWh
Energy Yesterday: EnergyYesterday kWh
WiFi RSSI: RSSI dBm
Wait 5Secs or Click this button to update data
Reference: JSON and AJAX