This site is mobile accessible. Press the "Tap Here" button to use a different font-size.


Smartphone icons created by Freepik - Flaticon

10.6 AJAX Poll

  • The following example will demonstrate a poll where the result is shown without reloading.

    Do you like PHP and AJAX so far?

    Do you like PHP and AJAX so far?

    Yes:

      No:

    Example Explained - The HTML Page

    When a user chooses an option above, a function called "getVote()" is executed. The function is triggered by the "onclick" event:

    <html>
    <head>
    <script>
    function getVote(int) {
      var xmlhttp=new XMLHttpRequest();
      xmlhttp.onreadystatechange=function() {
        if (this.readyState==4 && this.status==200) {
          document.getElementById("poll").innerHTML=this.responseText;
        }
      }
      xmlhttp.open("GET","poll_vote.php?vote="+int,true);
      xmlhttp.send();
    }
    </script>
    </head>
    <body>
    
    <div id="poll">
    <h3>Do you like PHP and AJAX so far?</h3>
    <form>
    Yes: <input type="radio" name="vote" value="0" onclick="getVote(this.value)"><br>
    No: <input type="radio" name="vote" value="1" onclick="getVote(this.value)">
    </form>
    </div>
    
    </body>
    </html>
    Yes: 5 45%
    No: 6 55%
    Navigate this module

    Eventually the navigation links, above, will be replaced by these << (previous) and >> (next) buttons below.



    Animated PHP icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon