Я создал простой, используя jQuery AJAX и JSON. Я хочу знать, как создать сеанс, чтобы пользователь не мог снова голосовать. Ниже мой код.
Я новичок в сессиях и JQuery. Пожалуйста, скажите мне, как выполнить мою задачу.
JavaScript
<script>
$(document).ready(function(){
$("#poll").click(function(){
var count = '';
if (document.getElementById("vote1").checked) {
count = 0;
}
if (document.getElementById("vote2").checked) {
count = 1;
}
var jsonV=
{
"vote": count
};
$.ajax({
type : "POST",
url : "poll_vote.php",
data : jsonV,
dataType: "json",
success : function (responseText){
console.log("Shit is working "+responseText);
$("#result").html(responseText.vote);
},
complete : function(){
$("#poll").slideUp();
},
error : function(error,responseText){
// alert("Server not Responding. Sorry for the inconvenience caused. Please Try again Later");
console.log(error);
$("#result").html(error+ responseText);
alert(count);
}
});
});
});
</script>
PHP
<?php
$vote = $_REQUEST['vote'];$filename = "poll_result.txt";
$content = file($filename);
// $decode = json_decode($encode);
$array = explode("||", $content[0]);
$male = $array[0];
$female = $array[1];
if ($vote == 0) {
$male = $male + 1;
}
if ($vote == 1) {
$female = $female + 1;
}
$insertvote = $male."||".$female;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
$table = (
"<h2>Results:</h2>
<table>
<tr>
<td> Male :</td>
<td>
<img src='poll.gif'
width= ".(100*round($male/($female+$male),2)).
"height='20'>".
(100*round($male/($female+$male),2))." %" .
"</td>
</tr>
<tr>
<td> Female :</td>
<td>
<img src='poll.gif'
width=". (100*round($female/($female+$male),2)) .
"height='20'>".
(100*round($female/($female+$male),2))." %" ."
</td>
</tr>
</table>");
$list = array('vote' => $table);
$encode = json_encode($list);
echo $encode;
?>
HTML
<div id= "poll">
<h3> What is your Gender? </h3>
<form>
Male :
<input type = "radio" name = "vote" id="vote1" >
<br>
Female :
<input type = "radio" name = "vote" id="vote2" >
</form>
</div>
<p><div id= "result"></div>
</body>
В верхней части кода PHP запустите сеанс, а затем проверьте, требуется ли значение сеанса, например:
<?php
session_start();
if(isset($_SESSION['voted']){
$list = array('vote' => 'You have already voted!');
$encode = json_encode($list);
echo $encode;
exit;
//or, shorter: die(json_encode(array('vote' => 'You have already voted!')));
}
$_SESSION['voted'] = 1;
//rest of your code here
Других решений пока нет …