The following example will demonstrate a poll where the result is shown without reloading.
Do you like PHP and AJAX so far?
Example Explained – AJAX Poll HTML Page
When a user choose an option above, a function called "getVote()" is executed. The function is triggered by the "onclick" event:
The getVote() function does the following:
- Create an XMLHttpRequest object
- Create the function to be executed when the server response is ready
- Send the request off to a file on the server
- Notice that a parameter (vote) is added to the URL (with the value of the yes or no option)
AJAX Poll PHP File
//get content of textfile
//put content in array
if ($vote == 0)
//insert votes to txt file
- Get the content of the "poll_result.txt" file
- Put the content of the file in variables and add one to the selected variable
- Write the result to the "poll_result.txt" file
- Output a graphical representation of the poll result
AJAX Poll Text File
The text file (poll_result.txt) is where we store the data from the poll.
It is stored like this:
The first number represents the "Yes" votes, the second number represents the "No" votes.
Note: Remember to allow your web server to edit the text file. Do NOT give everyone access, just the web server (PHP).