I've created a simple [voting form] using jQuery AJAX and JSON. I want to know how to create a Cookie so that the user will not be able to vote more than once. Following is my code.
I am new to Cookies and jQuery. Please tell me how to complete my task.
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("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>
You would want to set a cookie when the user votes, and check for that cookie in PHP when a vote is submitted. If the cookie is already set, the vote should be discarded.
For example, using just PHP, it could look something like this:
if (!isset($_COOKIE['has_voted'])) {
// normal vote submission code goes here
// ...
// then we set a cookie to expire in 30 days
setcookie('has_voted', '1', mktime().time()+60*60*24*30);
} else {
// cookie already exists, user has already voted on this machine
// do not count the vote, flag an error to the user
}
It is worth noting that there are ways round this - the user could easily delete the cookie manually. In this case, you could also store the IP addresses of users who have already voted, but this can open up problems on shared machines and multiple machines behind a network.
Since it seems you're using PHP, you'll be able to implement a cookie to prevent multiple votes within your already existing script.
The syntax for setting a cookie in PHP is as follows:
setcookie("cookiename", "cookiedata", cookietime, "cookielocation");
Where "cookiename" is the name of the cookie, for example, "voted", "cookiedata" is the data stored in the cookie– "yes", for example. "cookielocation" is the location where the cookie is stored in the user's browser cache. Unless you know what you're doing, just set this to "/".
Cookietime is how long the cookie will sit in the users system until the browser automatically deletes it. Note that this doesn't prevent the user from deleting the cookie. For simplicity, I usually set the time as follows:
time()+60*60*24*days
Where days is how long the cookie will sit in the user's system (in days, of course).
To retrieve the value of a cookie so you're able to perform logic on it, try using:
if(isset($_COOKIE['cookiename'])) {
$valueOfCookie = $_COOKIE['cookiename'];
}
Make sure to use the if(isset()) to make sure the cookie has been set, before trying to retrieve the value.
Using these functions, your logic may look something like this when the user submits the form:
Check if the voting cookie is set
If it is, print an error message, else:
Continue to process the form data, and set the vote cookie
However, on a side note, if you're concerned about users potentially deleting their cookies so they can vote again, I might suggest that, rather than using cookies, you store users' IP addresses on the server-side, and deny them voting access if their IP address has already voted.
You could do this with sessionStorage, using only JS:
<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 };
if ( sessionStorage.getItem( 'voted' ) == 'true' ) {
alert('You have already voted!');
}else if ( sessionStorage.getItem( 'voted' ) == null ){
$.ajax({
type : "POST",
url : "poll_vote.php",
data : jsonV,
dataType: "json",
success : function ( responseText ){
console.log("It's working" + responseText);
$("#result").html( responseText.vote );
},
complete : function(){
$("#poll").slideUp();
sessionStorage.setItem('voted', 'true');
},
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>
What I have done here is added a session storage item in the
complete callback of your ajax call, so once it has completed the
item 'voted' will be set.
I have then wrapped the ajax call in an if condition which checks
the value of the storage item and if it is set then will not allow
you to vote (and instead bring up an alert)
Note that you can also you localStorage if you want the item to last longer as sessionStorage is cleared when the browser window is closed while localStorge will last until the user clears their cookies / browsing data.
And here is a little snippet you can use to clear the storage for testing purposes:
$('#clear').click(function(){
console.log(sessionStorage.getItem( 'voted' ));
sessionStorage.removeItem('voted');
console.log(sessionStorage.getItem( 'voted' ));
});
You will need the accompanying HTML with that:
<p id="clear">clear</p>
Related
This question already has answers here:
Listening for variable changes in JavaScript
(29 answers)
Closed 5 years ago.
I currently have a div which displays information such as DNS and IP address.
I am trying to trigger an alert if the IP Address variable changes, so I've attempted both listening for changes to the div and the variable itself without much luck. Is there an obvious way to alert or trigger a function if the variable changes?
$(ipv4.ipaddr).change(function() {
alert("IP Changed");
});
And the script used to display the IP addr normally:
if(result.ipv4){
$("#btn-disconnect").show();
$("#btn-disconnect-modem").show();
var ipv4=result.ipv4;
html+="<tr><td>IPAddr</td><td>"+ ipv4.ipaddr+"</td></tr>";
if(ipv4.netmask) html+="<tr><td>Netmask</td><td>"+ ipv4.netmask+"</td></tr>";
if(ipv4.gateway) html+="<tr><td>Gateway</td><td>"+ ipv4.gateway+"</td></tr>";
label_dns="DNS";
for(var i=0;i<ipv4.dns.length;i++){
html+="<tr><td>"+label_dns+"</td><td>"+ ipv4.dns[i] +"</td></tr>";
label_dns="";
}
if(proto=="wwan" || proto=="tethering"||proto=="3g"){
if(result.tx) html+="<tr><td>TX Data</td><td>"+(result.tx/1024/1024>1? ((result.tx/1024/1024).toFixed(2)+" MB"): ((result.tx/1024).toFixed(2) +" KB") )+" </td></tr>";
if(result.rx) html+="<tr><td>RX Data</td><td>"+(result.rx/1024/1024>1? ((result.rx/1024/1024).toFixed(2)+" MB"): ((result.rx/1024).toFixed(2) +" KB") )+"</td></tr>";
}
if(typeof sta_connected === "function") sta_connected();
}else{
if( (proto=="wwan" ||proto=="tethering")){
if(!result.disabled) html+="<tr><td>Connecting to the Internet</td></tr>";
}
if(proto=="wisp" ||proto=="wds"){
if(!result.disabled) html+="<tr><td>Connecting to the Internet</td></tr>";
result.disabled? $("#btn-disconnect").hide():$("#btn-disconnect").show();
}
}
$(section).html(html);
}
I need the html to give a better answer but this one I am giving you already works! I suppose you use jQuery and you must know when you want to check the ip, i mean you can do it always putting an onclick method on the body (not recommened) or you can do it when the user press any available submit button in your form (I will explain this one). Check this out:
<script>
if($("input=[type=submit]").on('click',function(){
var lastip=document.getElementById("ip").value;
$.post("yourfile.php", { lastip: lastip }, function(data){
$("#yourdiv").html(data);
});
});
</script>
yourfile.php
function user_ip() {
$ip = '';
if (getenv('HTTP_CLIENT_IP'))
$ip = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ip = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ip = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ip = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ip = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ip = getenv('REMOTE_ADDR');
else
$ip = 'Not Available';
return $ip;
}
$lastip= $_POST['lastip'];
$nowip= user_ip();
if($nowip!=$lastip AND !empty($lastip)){
echo 'ip changed!';
exit();
}
<div id="yourdiv">
<table>
<tr>
<td id="ip">IP:<?php echo $nowip;?></td>
<td id="dns">DNS:</td>
</tr>
</table>
</div>
How about something like:
$(function() {
var ipAddress = ipv4.ipaddr
setInterval(() => {
if (ipAddress !== ipv4.ipaddr) {
var ipAddress = ipv4.ipaddr
alert('IP Has Changed!')
}
}, 1000)
});
This stores the current IP address in ipAddress on page load then every second it will check to make sure it's the same as the current ipv4.ipaddr and if it isn't - raise the alert saving the new value ready for the check to take place again.
Note: This assumes you're populating ipv4.ipaddr automatically somewhere.
Have a function that makes a change to taxonomy term via AJAX. This works great, except the content remains unchanged on window.location.reload(true) even though the change has been made. See the code and GIF below to understand.
This is an example that adds the button and reloads page on click
if ( 'publish' === $post->post_status && $post->post_type === 'campaigns' ) {
$text = (in_category( 'live') ? 'Activate' : 'Activate');
echo '<li>' . $text . '</li>';
}
So, is there another way that I can reload the page onClick that may help? Also, the post modified date is not updating, yet changes have been made to the post.
Thanks in advance for your help
EDIT -
I have already tried
location.href = location.href; and
document.location.reload();
ADDITIONAL INFO -
Function
add_action('wp_ajax_toggle_live', function(){
// Check ID is specified
if ( empty($_REQUEST['post']) ) {
die( __('No post ID specified.') );
}
// Load post
$post_id = (int) $_REQUEST['post'];
$post = get_post($post_id);
if (!$post) {
die( __('You attempted to edit an item that doesn’t exist. Perhaps it was deleted?') );
}
// Check permissions
$post_type_object = get_post_type_object($post->post_type);
if ( !current_user_can($post_type_object->cap->edit_post, $post_id) ) {
die( __('You are not allowed to edit this item.') );
}
// Load current categories
$terms = wp_get_post_terms($post_id, 'campaign_action', array('fields' => 'ids'));
// Add/remove Starred category
$live = get_term_by( 'live', 'campaign_action' );
$index = array_search($live, $terms);
if ($_REQUEST['value']) {
if ($index === false) {
$terms[] = $live;
}
} else {
if ($index !== false) {
unset($terms[$index]);
}
}
wp_set_object_terms( $post_id, 'live', 'campaign_action' );
die('1');
});
JS
function toggleLive(caller, post_id)
{
var $ = jQuery;
var $caller = $(caller);
var waitText = ". . .";
var liveText = ". . .";
var deactivateText = ". . .";
// Check there's no request in progress
if ($caller.text() == waitText) {
return false;
}
// Get the new value to set to
var value = ($caller.text() == liveText ? 1 : 0);
// Change the text to indicate waiting, without changing the width of the button
$caller.width($caller.width()).text(waitText);
// Ajax request
var data = {
action: "toggle_live",
post: post_id,
value: value
};
jQuery.post("<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php", data, function(response)
{
if (response == "1") {
// Success
if (value) {
$caller.text(deactivateText);
} else {
$caller.text(liveText);
}
} else {
// Error
alert("Error: " + response);
// Reset the text
if (value) {
$caller.text(deactivateText);
} else {
$caller.text(liveText);
}
}
// Reset the width
$caller.width("auto");
});
// Prevent the link click happening
return false;
}
IT WORKS RIGHT ON PAGE THAT ISN'T SINGULAR
Is toggleLive the function that makes the AJAX request? You are calling reload immediately on click before changes are reflected on the backend. If you are using Jquery include your reload code in the complete callback function that indicates completion of your AJAX request.
Try using Live Query plug-in in jquery instead of live .
I was able to achieve this by setting return trueOrFalse(bool); in the JS and adding the permalink for the page into <a href=""> within the function.
I believe #cdoshi was correct in their answer, yet I was unable to achieve this. I am sure that a little further exploration would make this possible, yet my fix achieved what I wanted with little change to my code.
I'm a student and still new with Javascript and php, i need to make a login page for my website that can check user input in the database using ajax.
Example: When the user enter their username and password into the field given,the system will automatically check in database either the user exist or not and return the data needed such as user responsibilty from the response table to the dropdown menu below, then they can login into the system.
Below is my basic coding:
Config.php:
e$host = "localhost";
$User = "root"
$Pass = "passw";
$db = "skm_spm";
Login.php:
<?
require ("config.php");
$conn=mysqli_connect($host,$user,$pass,$db);
$duser="select * from tab_user where user_name = '".$_POST["Lname"]."'";
$uresult=myqli_query($conn,$duser);
if(!$uresult)
die("Invalid query: ".mysqli_error());
else
if(mysqli_num_rows($uresult)== 0){
echo "User does not exist";
}
else
{
$row=mysqli_fetch_array($result,MYSQL_BOTH);
if($row["User_Password"] == $_POST["Lpass"])
{
$dresp="select resp_id,resp_name from tab_resp";
$result2 = mysqli_query($conn,$dresp);
}
else
{
}
}
?>
<html>
<b>Login</b><br>
Name : <input type = "text" name="Lname" id="Lname" placeholder="Username"/><br>
Password: <input type = "password" name="Lpass" id="Lpass" placeholder="password"/><br><br>
<div class = "optresp">
<select name="sresp" id="sresp">
<option>--Responsibility--</option>
<?
while (mysqli_fetch_array($result2)){
echo "<option value='$row[1]'>$row[1]</option>";
?>
</select>
</div>
</html>
I have learn on internet and try to code with my understanding,but still failed. I need a php ajax coding that can work with code above.
Thank you.
I will provide you with some code from my recent project and hopefully you will be able to understand it and adapt it to your needs.
Firstly, you should have the login form in a separate file to the PHP login code. Then have button on the page or an enter events that run a Javascript function, in my case Login(). In this Javascript function the text within the input fields are saved to two variables and some basic checks are done on them to ensure that they have been filled in. Next, the PHP login function file (it has no visible content in just processes some data in PHP) using the $.post line. This also passed the two input variables (under the same name) to the PHP file. You can also see that depending on what is returned/echoed from the PHP file as "data" several possible outcomes may occur (Login Success, Account Banned or Invalid Login). I personally call these outcomes error messages or success messages, for example error message 6 for incorrect password/username.
//FUNCTIONS
function Login(){
var StrUsername = $("#txtUsername" ).val();
var StrPassword = $("#txtPassword").val();
if (StrUsername == "" && StrPassword == ""){
$('#pError').text('Enter your Username and Password!');
}
else if(StrUsername == ""){
$('#pError').text('Enter your Username!');
}
else if(StrPassword == ""){
$('#pError').text('Enter your Password!');
}
else{
$.post('https://thomas-smyth.co.uk/functions/php/fnclogin.php', {StrUsername: StrUsername, StrPassword: StrPassword}, function(data) {
if (data == 0){
window.location.href = "https://thomas-smyth.co.uk/home";
}
else if (data == 1){
window.location.href = "https://thomas-smyth.co.uk/banned";
}
else if (data == 6){
$('#pError').text('Username & Password combination does not exist!');
}
});
}
}
Next the PHP function file. Firstly, the variables passed by the Javascript are collected using $_POST. My SQL class is then pulled into the file, this does all my SQL DB connections. I then have my SQL statement that will search to see if the account exists. Notice the ? in it. This prevents SQL injections as the variables is bound into the statement through the SQL server meaning it won't allow people to put SQL code within my input fields to break my database. I then check whether the account exists, if it doesn't I save data to 6, which will cause the error message 6 in the Javascript to run when data is returned. I have a field in my database that contains a rank. If the login is correct then I create a SESSION variable to store their username and rank in. This is later used on pages to check whether they are logged in before displaying a page (this speeds up navigation as it means that the DB doesn't need to be searched everytime the user switches page, however does bring some issues like if you ban a user while they are logged in they will stay logged in until their session dies). You could use this on your dropdown menu to ensure the user is logged in and/or get their username. Finally, I return 0 or 1, so that the Javascript then re-directs them to the correct page.
<?php
//Retrieves variables from Javascript.
$StrUsername = $_POST["StrUsername"];
$StrPassword = $_POST["StrPassword"];
require "sqlclass.php";
$TF = new TF_Core ();
$StrQuery = "
SELECT Username, Rank FROM tblUsers
WHERE Username = ? AND Password = ?";
if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
$statement->bind_param('ss',$StrUsername,$StrPassword);
$statement->execute ();
$results = $statement->get_result ();
if($results->num_rows == 0){
$data = 6;
}
else {
while ($row = $results->fetch_assoc()) {
//Other groups
if ($row["Rank"] == "Developer" || $row["Rank"] == "Staff" || $row["Rank"] == "Cadet"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, $row["Rank"]);
$data = 0;
}
//Banned
else if ($row["Rank"] == "Banned"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, "Banned");
$data = 1;
}
}
}
}
echo $data;
?>
Hopefully this helps you. Please say if you need more help!
You need to make ajax call on blur of username to check if user exists in database and on success of that you can make one more ajax to check for password match of that particular user. This will give you both cases whether a user exixts or not if exixts then does the password match or not only after that user will be logged in and then you can show the responsibilities of that particular user.
For username:
$('#Lname').blur(function(){
$.ajax({
url:'url where query for matching username from database',
data:'username collected from input on blur',
type:'POST',
success:function(data){
//Code to execute do on successful of ajax
}
})
})
For Password:
The ajax call remains the same only url, data and response changes
I have one checkbox on my form working with the database for active(1) and inactive(0) users to access via admin panel. All is working fine but the problem is its not keeping the record for the checboxes when the checkbox is checked or unchecked after refreshing/reloading the page. i want them to be remembered even after admin logout and login again. can any one help me out ?
Thanx in advance
Here is HTML :
<td><input type='checkbox' class='user_status'
id='user_status_<?php echo $data['user_reg_id']; ?>' value='' name = 'user_status'
onclick="userId(<?php echo $data['user_reg_id']; ?>)" />
Here is JS :
<script>
function userId(user_reg_id){
$(document).ready(function(){
var link = "<?php echo base_url();?>" ;
var st = $('#user_status_'+user_reg_id).is(":checked") ? 0 : 1;
$.post(link + "administration/um/user_status", {user_reg_id:user_reg_id, user_reg_status:st, ajax : 1}, function(data){
alert (st); //showing status 1 and 0 on alert
if (st == 1){
$("#user_status_").prop(":checked", true)
} else {
$("#user_status_").prop(":checked", false)
};
});
});
}
</script>
store checkbox value in database using ajax when you click on it..
also fetch from database checkbox value if checkbox value is 1 than checked ...otherwise uncheck :)
Since you need the data to be persistent, I would suggest using HTML5 localStorage. Depending on how persistent, you may need to save it in a database. I haven't tested this code and have not actually done this. It's meant to get you close to a working solution.
function isChecked(user_reg_id){
$(document).ready(function(){
$('#user_status_'+user_reg_id).on('click', function () {
if(localStorage && localStorage.getItem(user_reg_id)){
localStorage.removeItem(user_reg_id);
}else{
$('#user_status_'+user_reg_id).prop('checked', true);
}
}
});
}
I am trying to create a form that, once submitted, will be sent to my index.html page for other users to view. I want it so multiple users anywhere in the world can submit information and so the website displays all their information at once.
Here is my submit page's PHP code:
<form action="submit_a_message.php" method="post">
<textarea name="message" cols="60" rows="10" maxlength="500"></textarea><br>
<input type="submit">
</form>
I am trying to figure out how to make the information submited via that form appear on my index.html page. This is the code I found online, but it doesn't work. Why?
<?php>
string file_get_contents ( string $submit_a_message.php [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )
<?>
Any help would be greatly appreciated.
To make submitted text avaliable on your index page, you need a place where you would store it. You can use MySQL base to do that, or (if you can't or you really don't want) you can use text file with your texts/posts (that is not really good way, i warned you).
To do that with MySQL you can use a code like this on your submit_a_message.php:
<?php
//connection to database and stuff
...
if $_POST['message'] {
$message = $_POST['message'];
$sql = "insert into `mytable` values $message"; //that is SQL request that inserts message into database
mysql_query($sql) or die(mysql_error()); // run that SQL or show an error
}
?>
In order to show desired vaues from table use above-like idea, your SQL request would be like select * from mytable where id = 123
if your not married to the idea of using php and learning how to manage and access a database you could use jquery and a trird party backend like parse.com
If your new to storing and retrieving data, I would definately reccomend the services that https://parse.com/ offeres. It makes storing and retrieving data trivial. Best of all, the service is free unless your app makes more than 30 API requests per second. I have an app that 61 users use daily and we have never come close to the 30 req per second limit.
To save your info, you could write:
$('document').ready(function(){
$('#submit_btn').on('click',function(){ // detect button click, need to add "submit_btn" as the id for your button
var Message = Parse.Object.extend("Message"); //create a reference to your class
var newObject = new EventInfo(); //create a new instance of your class
newObject.set("messageText", $("#myMessage").val()); //set some properties on the object, your input will need the id "myMessage"
newObject.save(null, { //save the new object
success: function(returnedObject) {
console.log('New object created with objectId: ' + returnedObject.id);
},
error: function(returnedObject, error) {
console.log('Failed to create new object, with error code: ' + error.message);
}
});
});
});
Retrieving that info later would be as easy as:
var Message = Parse.Object.extend("Message"); //create a reference to your class
var query = new Parse.Query(Message); //create a query to get stored objects with this class
query.find({
success: function(results) { //"results" is an array, you can fine tune your queries to retrieve specific saved objects too
for (var i = 0; i < results.length; i++) {
var object = results[i];
$(body).append("Message #" + (i+1) + object.get("messageText");
}
},
error: function(error) {
console.log("Failed to complete Query - Error: " + error.code + " " + error.message);
}
});