I have this fiddle where when the user clicks a button the counter works: http://jsfiddle.net/z66WF/
This is the code:
<button type="button" onClick="clickME()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
var clicks = 0;
function clickME() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
}
The problem is that I want the number to be saved, so for example:
user #1 clicks on the button 10 times
user #2 opens the site and the count is at 10, he clicks and now the counter starts 11
and so on with new users.
I'm trying to do this to keep track of how many times a file has been downloaded.
Any idea how can I do that?
Here you have a working simple exemple, wich write the counter in a simple txt file (no sql db needed)
<?php
$counterFile = 'counter.txt' ;
// jQuery ajax request is sent here
if ( isset($_GET['increase']) )
{
if ( ( $counter = #file_get_contents($counterFile) ) === false ) die('Error : file counter does not exist') ;
file_put_contents($counterFile,++$counter) ;
echo $counter ;
return false ;
}
if ( ! $counter = #file_get_contents($counterFile) )
{
if ( ! $myfile = fopen($counterFile,'w') )
die('Unable to create counter file !!') ;
chmod($counterFile,0644);
file_put_contents($counterFile,0) ;
}
?>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
jQuery(document).on('click','a#download',function(){
jQuery('div#counter').html('Loading...') ;
var ajax = jQuery.ajax({
method : 'get',
url : '/test.php', // Link to this page
data : { 'increase' : '1' }
}) ;
ajax.done(function(data){
jQuery('div#counter').html(data) ;
}) ;
ajax.fail(function(data){
alert('ajax fail : url of ajax request is not reachable') ;
}) ;
}) ;
</script>
</head>
<div id="counter"><?php echo $counter ; ?></div>
Download btn
You need a DB connection to do this.
When the button is clicked, by any user, the value from let's say: "downloaded_times" will be increased with 1.
so you will need a query like:
UPDATE table SET downloaded_times = downloaded_times + 1
this query will be called each time someone presses the button.
If you want to display it, before a certain user wants to start a download, you simply fetch the result from DB and the echo it. You can do more, if you want that field to be constantly refreshed, the fetching and echoing part should be in a ajax called PHP function, that will refresh the div (for instance) every 30 second or so :D
Hope this helps! :D
Related
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>
I designed a site that gets news from another site's RSS and saves it to my DB. To do this I must send request to another site and save changes to my DB.
this is my code for sending request:
$q = $d->query("select * from site_setting where id=1");
$setting = $d->fetch($q);
$start = $setting['last'];
$q = $d->query("select *from newsagency order by id limit ".$start.",1");
while($agency = $d->fetch($q)){
$url = $agency['link'];
$size = 20;
$agencyId = $agency['id'];
$time = time();
RSS_RetrieveLinks($url);
if($size > 0)
$recents = array_slice($RSS_Content, 0, $size + 1);
$MaxTime = $d->getrowvalue("time","select `time` from news where agency={$agencyId} order by time DESC limit 0,1",true);
foreach($recents as $article)
{
$articleTime = strtotime($article["date"]);
if($articleTime > ($MaxTime+1)){
$d->iquery("news",array(
'title'=>htmlspecialchars($article["title"]),
'time'=>$articleTime,
'link'=>$article["link"],
'type'=>$article["type"],
'img'=>$article["media"],
'regTime'=>$time,
'agency'=>$agencyId
));
$return .= $article['title']."<br>";
}
}
}
$last = $start +1;
$agencyCount = $d->getrowvalue("agenC","select count(id) as agenC from newsagency",true);
$agencyCount--;
if($last>$agencyCount) $last = 0;
$d->uquery("site_setting",array('last'=>($last)),"id=1");
this code gets rss link one by one from db and then gets data from rss and saves it to db, and everything in OK. to refresh the php page, we have a code like this :
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$.ajax({
url: "load.php",
context: document.body,
success: function(vars){
document.getElementById("imge").innerHTML+=vars;
}
})
}, 500);
});
</script>
</head>
<body dir="rtl">
<div id="imge"></p>
</body>
I refresh this code every 500 ms and get content from rss. The problem is that this page must forever be open and I don't have any idea to solve this problem. How can I send this request without getting the client's computer busy?
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'm currently using this code on my webpage:
<?php
$url = "https://www.toontownrewritten.com/api/invasions";
$data = json_decode(file_get_contents($url));
if (!empty($data->invasions)) {
echo "<h1 style='text-align:center;margin:auto;padding:2px;font-size:16px;font-weight:bold;text-decoration:underline;padding:2px;'>Invasion Tracker</h1>";
$i = 0;
foreach($data->invasions as $title => $inv) {
print "<h3 style='text-align:center;margin:auto;'><b>District:</b> {$title}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Cog:</b> {$inv->type}
</h3><br style='font-size:1px;'><h3 style='text-align:center;margin:auto;'><b>Progress:</b> {$inv->progress}
</h3>";
if (count(($data->invasions) > 1)) {
if (end($data->invasions) !== $inv) {
print "<hr>";
} else {
print "<br style='font-size:2px;'>";
}
}
}
} else {
echo "<h1 style='text-align:center;margin:auto;padding:2px;color:darkred;font-weight:bold;'>No invasions!</span>";
}
?>
I'm looking to make it refresh every 10 seconds via AJAX. However, I keep reading you need to make a function, but I'm not sure how I'd do that with the API? Every 10 seconds, that API is being updated, which is why I'd like this to be updated with AJAX every 10 seconds. Currently, I have it so the user has to manually refresh. Any help is appreciated!
You can simply reload the page with the method proposed here
But if you wanna have an AJAX implementation which just refereshes a part of your html nice and tidy, You gonna have to
Almost forget your PHP code
use the following code to implement the request to the url
$.ajax({
url: "https://www.toontownrewritten.com/api/invasions",
})
.done(function( data ) {
if ( console && console.log ) {
console.log( data );
}
});
Make a JS code which would convert the data got in the previous section to a readable html and show it on your page. It should be implemented in the the block where console.log(data) is.
Put that part of code in a setInterval
setInterval(function(){
//$.ajax();
}, 10000);
And be aware that you are gonna go to hell if your request doen't complete in the interval. see this .
I have a better suggestion, again it is same as using setInterval.
setInterval(function () {
if (isActive) return; // so that if any active ajax call is happening, don't go for one more ajax call
isActive = true;
try {
$.ajax("URL", params,function() { isActive = false;//successcallback }, function () {
isActive = false; // error callback
});
} catch (ex) { isActive = false;}
}, 10000);
Your problem is a failure to understand AJAX. Below is a $.post() example.
First let's make the page that you want your Client (the Browser user) to see:
viewed.php
<?php
$out = '';
// you could even do your initial query here, but don't have to
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<style type='text/css'>
#import 'whatever.css';
</style>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='whatever.js'></script>
</head>
<body>
<div id='output'><?php /* if initial query took place */ echo $out; ?></div>
</body>
</html>
Now you need your JavaScript in whatever.js.
$(function(){
function getData(){
$.post('whatever.php', function(data){
// var htm = do a bunch of stuff with the data Object, creating HTML
$('#output').html(htm);
});
}
getData(); // don't need if PHP query takes place on original page load
setInterval(getData, 10000); // query every 10 seconds
});
On whatever.php:
<?php
// $assocArray = run database queries so you can create an Associative Array that can be converted to JSON
echo json_encode($assocArray);
?>
The JSON generated by PHP shows up in the data argument, back in the JavaScript that created your PHP request:
$.post('whatever.php', function(data){
I have button which in enclosed by <a> tag. When clicked, it executes redirect.php script.
login.php - contains
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>
redirect.php contains twitter authentication code. If authenticated successfully then gives id and name. I want to fetch these both value in index.php
Using ob_start(); I can receive values from php script to JS function via json.
But I am confused about how to manage the code in index.php to execute script on button click and receiving these two value also.
redirect.php
<?php
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
header('Location: ./clearsessions.php');
}
$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$content = $connection->get('account/verify_credentials');
$twitteruser = $content->{'screen_name'};
$notweets = 5;
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);
$id = $content->{'id'};
$name = $content->{'name'};
?>
Please let me know if you need further explaination.
Bottomline:
Rather executing redirect.php script on link click, I want it to execute via function on button click event.
Getting id and name from redirect.php to index.php after redirect script executed
I already have session_start() to manage the twitter session. So dont want to mess up using mutiple session if not necessary ..
UPDATE after david's answer
<body>
<input type="button" value="Run somePHPfile.php" id = "b1" />
<script>
$('#b1').click(function () {
window.location.href = 'redirect.php';
$.get('index.php', function(data) { //If I put this out side click then it gives undefined value for name and id before redirect.php gets executed
// data.id is the id
var id= data.id;
var name = data.name;
alert(name);
});
});
</script>
</body>
Apologize to say:
On button click redirect.php script executed. redirect.php includes other files, which finally reach to index.php. And index.php returns name and id.
So is this enough to manage it : $.get('index.php', function(data) { ... }
To bind to a click event of an HTML button, you would use JavaScript. Since you tagged the question with jQuery, I'll assume its use. The event handler would look something like this:
$('#loginButton2').click(function () {
window.location.href = 'redirect.php';
});
Note: This simulates an anchor click effectively. If you instead want to more closely resemble an HTTP redirect, you might want to use this instead:
window.location.replace('redirect.php');
As for the id and name values, how exactly does this flow return the user to index.php in the first place? Your redirect.php has, well, a redirect (though not all code paths result in that) so it kind of assumes non-AJAX interaction. (I think XHR follows redirects sometimes, but the behavior is different from one browser to another.)
If the redirect isn't terribly important and you just want to make an AJAX call to redirect.php, then you can do that with a simple AJAX request:
$.get('redirect.php');
In order to get those values back to the page, they'll need to be emitted from redirect.php. Something like this:
echo json_encode((object) array('id' => $id, 'name' => $name));
Then in the client-side code you would have those values available in the AJAX callback:
$.get('redirect.php', function(data) {
// data.id is the id
// data.name is the name
// use these values client-side however you need
});
<script>
$("#loginButton2").on('click',function(){
window.location.href="redirect.php";
});
</script>
and in redirect.php file
$_SESSION['id']=$id ;
$_SESSION['name']=$name;
and also
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>
to
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>