Starting Electronics Needs Your Help!
It is that time of the year when we need to pay for web hosting and buy new components and equipment for new tutorials. You can help by making a donation. Contribute to this website by clicking the Donate button. The total will be updated once daily. (You may need to clear your browser cache to see the updates.)
Target Amount: $2000
Amount Raised: $359
Top Donor: D.C. $30
Created on: 13 February 2013
Part 8 of the Arduino Ethernet Shield Web Server Tutorial
Before continuing with this part of the tutorial, you will need to have completed the previous part of this tutorial and understand it.
This video shows the Arduino web server displaying the switch status automatically using AJAX.
Can't see the video? View on YouTube →
Use the same hardware as the previous part of this tutorial – a push button switch interfaced to pin 3 of the Arduino with Ethernet shield.
Only three modifications need to be made to the previous sketch (eth_websrv_AJAX_switch) to automate the AJAX call that updates the switch status on the web page.
The modified sketch is shown here:
The image below shows the modifications that were made to the HTML file that the Arduino sketch sends to the web browser (this file is sent line by line using client.println() in the sketch).
Firstly, the code that creates a button on the web page has been removed as the button is no longer needed. It can be seen commented out in the above image.
The GetSwitchState() function that was previously being called each time the button was pressed is now being called when the page is loaded. This is done by calling the function when the page load event occurs by modifying the <body> tag of the HTML: <body onload="GetSwitchState()">
This is added to the Arduino sketch with the following line of code:
The GetSwitchState() function would only be called once when the web page loads, unless we change the code to periodically call this function.
The following line of code is added to the bottom of the GetSwitchState() function to make sure that this function is called every second:
This code is added to the web page by adding this line to the Arduino sketch: