WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP Example - AJAX Poll


In this part we learn AJAX Poll

AJAX Poll

The beneath model will exhibit a survey where the outcome is appeared without reloading.

We can make PHP and AJAX so far?

Truly:
No:

Example Explained - The HTML Page

When a client picks a choice over, a capacity called "getVote()" is executed. The work is activated by the "onclick" event:

<html>
<head>
<script>
work getVote(int) {
  in the event that (window.XMLHttpRequest) {
   /code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { /code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("poll").innerHTML=xmlhttp.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>

The getVote() work does the below:

  • Create a XMLHttpRequest object
  • Create the capacity to be executed when the server reaction is ready
  • Send the demand off to a document on the server
  • Notice that a parameter (vote) is added to the URL (with the estimation of the yes or no option)

The PHP File

The page on the server called by the JavaScript above is a PHP record called "poll_vote.php":

<?php
$vote = $_REQUEST['vote'];

/get substance of textfile
$filename = "poll_result.txt";
$content = file($filename);

/place content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

on the off chance that ($vote == 0) {
  $yes = $yes + 1;
}
on the off chance that ($vote == 1) {
  $no = $no + 1;
}

/embed votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>

<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>

The esteem is sent from the JavaScript, and the underneath happens:

  1. Get the substance of the "poll_result.txt" file
  2. Put the substance of the record in factors and add one to the chose variable
  3. Write the outcome to the "poll_result.txt" file
  4. Output a graphical portrayal of the survey result

The Text File

The content record (poll_result.txt) is the place we store the information from the survey.

It is put away like this:

0||0