2015-04-18 64 views
3

我已经创建了简单的使用jQuery AJAX和JSON。我想知道如何创建会话,以便用户不能再次投票。以下是我的代码。创建一个会话不要再投票投票

我是新来的Sessions和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> 
+0

饼干将是一个更好的选择,我猜。 – lshettyl

+0

使用'session_start()'function.and设置会话变量。''__SESSION [“login”] =“green”;' – SoftwareDev

+0

@LShetty你能告诉我该怎么做吗? –

回答

0

在你的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 
+0

谢谢。它的工作:) –

+0

做到了。你能告诉我如何在cookies中做到这一点? –

+0

同样的方法,只需用$ _COOKIE替换$ _SESSION即可。 –