Is there a way to call Javascript functions from an ESP?
I don't want to call AJAX requests every few seconds; I want to update my values only when they change.
Can it by done?
Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It only takes a minute to sign up.
Sign up to join this communityIs there a way to call Javascript functions from an ESP?
I don't want to call AJAX requests every few seconds; I want to update my values only when they change.
Can it by done?
If you want server-push, you can use Server Sent Events or a Websocket instead of polling with XMLHttpRequest.
So yes, it can be done, and I have implemented both using a Nano 33 IoT at one end and Javascript in a browser on the other. Some example code is here: https://github.com/ocrdu/arduino-webinterface-sse and here: https://github.com/ocrdu/arduino-webinterface-websocket.
I don't know if there are convenient libraries for the ESPs to do this, though.
I assume that you misunderstand how JavaScript works. JS is executed on the client side and therefore the esp can easily serve JS code the same way it would provide any html content. Take a look at the Webserver examples and embed your JavaScript code into the html content that the examples use.
The important thing to note is that the esp does not execute JavaScript, from its perspective the content is just an ordinary string without functionality.
The easiest and fastest way to update values on a web interface is probably using a websocket: the esp is a websocket server (using link2004‘s websocket library) and the JavaScript binds to the esp‘s websocket as a client (this has nothing to do with the esp/arduino/C++, but you’ll find examples out there).