Help with displaying a list with ajax
Posted: Sat Mar 24, 2018 6:52 am
I'm trying to make a page display a shopping list that I can add items to via Google Assistant and IFTTT and have that list update without a browser refresh.
I have almost everything working except when a new item is added it is on the same line as the previous item. If I try to add HTML code to the String with the list item data the page won't update automatically. If I refresh the page the list displays in the format I want, however. This is what I have so far
I have almost everything working except when a new item is added it is on the same line as the previous item. If I try to add HTML code to the String with the list item data the page won't update automatically. If I refresh the page the list displays in the format I want, however. This is what I have so far
Code: Select all
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
ESP8266WebServer server(1066);
const char* ssid = "";
const char* password = "";
String Website, data, XML, Javascript;
void javascriptContent(){
Javascript = "<SCRIPT>\n";
//Javascript += "alert('hello');\n";
Javascript += "var xmlHttp=createXmlHttpObject();\n";
Javascript += "function createXmlHttpObject(){\n";
Javascript += "if(window.XMLHttpRequest){\n";
Javascript += "xmlHttp=new XMLHttpRequest();\n";
Javascript += "}else{\n";
Javascript += "xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');\n";
Javascript += "}\n";
Javascript += "return xmlHttp;\n";
Javascript += "}\n";
Javascript += "\n";
Javascript += "function response(){\n";
Javascript += "xmlResponse=xmlHttp.responseXML;\n";
Javascript += "xmldoc = xmlResponse.getElementsByTagName('data');\n";
Javascript += "message = xmldoc[0].firstChild.nodeValue;\n";
Javascript += "document.getElementById('div1').innerHTML=message;\n";
Javascript += "}\n";
Javascript += "function process(){\n";
Javascript += "xmlHttp.open('PUT','xml','true');\n";
Javascript += "xmlHttp.onreadystatechange=response;\n";
Javascript += "xmlHttp.send(null);\n";
Javascript += "setTimeout('process()',500);\n";
Javascript += "}\n";
Javascript += "</SCRIPT>\n";
}
void WebsiteContent(){
javascriptContent();
Website = "<html>\n";
Website += "<body onload ='process()'>";
Website += "<div id='div1'>"+data+"</div></body></html>";
Website += Javascript;
server.send(200, "text/html", Website);
}
void XMLcontent(){
XML = "<?xml version = '1.0'?>";
XML += "<data>";
XML += data;
XML += "</data>";
server.send (200, "text/xml", XML);
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid,password);
while(WiFi.status() != WL_CONNECTED) delay(500);
WiFi.mode(WIFI_STA);
Serial.print(WiFi.localIP());
server.on("/", WebsiteContent);
server.on("/xml", XMLcontent);
server.on("/text", textArg);
server.begin();
}
void textArg(){
data += server.arg("text");
Website = "<html>"+data+"</html>";
Serial.println(data);
server.send(200, "text/plain", Website);
}
void loop() {
server.handleClient();
}