i was looking to use a counter on my site so when anyone clicks certain buttons it adds +1 to the counter. I want it so that when you refresh the page the number stays the same, and when a different user clicks the button then it just adds +1 to the counter.
Is this possible? I'm fairly new to Javascript & Jquery so if you could explain it all out it would be great.
Thanks in advance.
Using AJAX and PHP to communicate with a file on the server:
(save this code in a file as index.php and you're good to go!)
There might be an easier way to do it, but I'll show you how to do it using AJAX (n*o page refresh*) and PHP that will allow you to do whatever you want with that counter value in JS.
The provided PHP is not the most secure in the world, but might be secure enough for your needs.
It will create automatically a file called counter.txt if there's none on your server folder (same path as index.php file).
By clicking any of the button elements (it's up tu you to change the jQuery selector) the AJAX get will read from the file the current value stored in your file and will than send an incremented counter value.
<?php
$file = 'counter.txt';
// CREATE FILE
if(!file_exists($file)){
$create = fopen($file, 'w') or die("Could not create the counter database.");
file_put_contents( $file , '0' );
fclose($create);
}
// WRITE FILE
if( isset($_POST['count']) ){
$msg = htmlentities(strip_tags($_POST['count']), ENT_QUOTES);
file_put_contents($file, $msg);
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Flat-File db counter with PHP and AJAX by roXon</title>
</head>
<body>
<button>click me</button>
<button>click me too!</button>
refresh the page , the counter should be memorized from our auto-generated database file! ;)
<br><b></b>
<script>
function addCount( newCounterValue ){
$.ajax( {
type: "POST",
data: {count : newCounterValue},
cache: false,
async: false,
success: function() {
$('b').append('<br>Succesfully sent: '+ newCounterValue);
}
});
}
$(function(){
$('button').click(function(){
$.get('counter.txt', function(data) {
// READ
var counter = parseInt(data, 10) || 0;
$('b').html('Retrieved counter from database = '+ data);
// SEND
addCount( ++counter ); // send preIncremented COUNTER
});
});
});
</script>
</body>
</html>
A client-side solution (will not be available to other users!) would be using HTML5 localStorage
LIVE DEMO
var counter = localStorage.getItem('counter') || 0;
$('button').click(function(){
localStorage.setItem('counter', ++counter);
alert(counter);
});
NOTE this is client side only. You can take a look at PHP how to create a file on the fly and send that value into that file.
On click I'd suggest you to use AJAX to contact that file and read the current value before updating it with PHP.
Related
I've got a basic like button concept on my site that visits url.tld?action=love and adds +1 to the link's database column.
It's a hassle redirecting to another page all the time though. Is it possible to click the button, and send a request to the URL without actually redirecting to a new URL? Also maybe refresh the button afterwards only so that the count updates?
For a general idea of what my download button is this is in the header:
<?php require_once('phpcount.php'); ?>
<p class="hidden"><?php
$time = time();
for($i = 0; $i < 1; $i++)
{
PHPCount::AddHit("$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]", "127.0.0.1");
}
echo (time() - $time);
/*echo "PAGE1 NON: " . PHPCount::GetHits("page1") . "\nPAGE1 UNIQUE: " . PHPCount::GetHits("page1", true);
echo "\n\n" . PHPCount::GetHits("page2");
$ntot = PHPCount::GetTotalHits();
$utot = PHPcount::GetTotalHits(true);
echo "###$ntot!!!!$utot";*/?></p>
And this is an example of my "love" button.
Love <span class="count">'. PHPCount::GetHits("$package_get?action=love", true).'</span>
The reason I used this method is because people create pages, and I wanted the like button to work out of the box. When their page is first visited it adds their url to the database, and begins tallying unique hits.
This is basically adding a new link column called downloadlink?action=love, and tallying unique clicks.
use the following code. assgin id="btn_my_love" to that button and add this code to you page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
//assign url to a variable
var my_url = <?php echo "https://alt.epicmc.us/download.php?link='.strip_tags($package_get).'?action=love"; ?>;
$(function(){
$("#btn_my_love").click(function(){
$.ajax({
url:my_url,
type:'GET',
success:function(data){
//comment the following result after testing
alert("Page visited");
},
error: function (request, status, error) {
alert(request.responseText);
}
});
//prevent button default action that is redirecting
return false;
});
});
</script>
Yes, it is possible. I am assuming you know what ajax is and how to use it, if not I am not going to give you the code because some simple reading on ajax as suggested by #Black0ut will show you how. But the basic steps are as follows:
Send ajax request to a PHP script that will update +1 vote to the database
In the PHP script, add +1 to the database and return some data to the ajax, maybe the new number of votes
Parse the return data in your JavaScript and update the button accordingly
I'm looking for the easiest way to add a simple like button to my site. Basically, a button that, when clicked - changes to a new graphic (letting you know you clicked it), can't be clicked again, and sends to a php script so the server knows what you liked.
I thought a good technique might be putting a like button inside an iframe so you can click it and the php page could just echo 'thanks for liking this' - but the problem is the iframe has to have a source. I don't want a ton of external files loading into each page. Is there any way I could just have an iframe tag and put HTML inside it without it being external?
Hopefully this makes sense. I do not know your server structure, so its hard for me to build a complete example but this should get you off your feet!
File: Index.php
// query the database and check to see if there is a record for this content piece and ip address
// select count() from statistics where contentId='1' and ip='0.0.0.0' limit 1;
$contentLiked = false;
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="site.js"></script>
</head>
<body>
<? if(!$contentLiked): ?>
like
<? else: ?>
unlike
<? endif ?>
</body>
</html>
File: site.js
$(document).ready(function() {
$('.likeButton').click(function() {
var contentId = $(this).attr('rel');
var link = this;
if(!$(link).hasClass('liked')) {
$.post("like.php", { Id: contentId }).done(function(data) {
if(data) {
$(link).addClass('liked');
$(link).html('liked');
}
});
}
});
});
File: like.php
<?
$contentId = $_POST['Id'];
$timestamp = time();
$usersIP = $_SERVER['REMOTE_ADDR'];
// php code to update the database
// insert: contentId, timestamp, ip address
// if injected then echo / print true;
echo 'true';
?>
You should use jquery animate. It allows you to create an animation on a HTML element that you choose with jquery.
With Jquery, using the 'click' event, you can use the animate effect, and have something like this:
$("#my-button").click(function(){
$(this).animate({
height: 'toggle'
}, 500, function(){
$(this).animate({
height: 'toggle'
}, 500);
});
});
Please see the following example of doing that
I have a Javascript function I'm rendering on a page where the user can click on a list element and it will bring them to a new page showing more information about that list element. The original page is #index and the second page is #index2 which is coded using one multipage HTML page.
However I am hoping that I can move the index2 page to its own html file - index2.html but I'm not sure how I can reference the new index.html file within the function so that the elements can move to the new file.
My code is as follows:
<script type="text/javascript">
$(document).on('pagebeforeshow', '#index', function(){
$("#list").empty();
var url="http://localhost/tmp/json4.php";
$.getJSON(url,function(json){
//loop through deals
$.each(json.deals,function(i,dat){
$("#list").append("<li><a id='"+dat.dealid+"' data-restaurantid=" + dat.restaurantid + " data-image=" + dat.image + "><h1>"+dat.name+"</h1><h6>"+dat.dname+"</h6><h5>"+dat.description+"</h5></a></li>");
$(document).on('click', '#'+dat.dealid, function(event){
if(event.handled !== true)
{
dealObject.dealID = $(this).attr('id');
dealObject.restaurantid = $(this).attr('data-restaurantid');
dealObject.shortName = $(this).find('h1').html();
dealObject.image = $(this).attr('data-image');
dealObject.dealName = $(this).find('h6').html();
dealObject.description = $(this).find('h5').html();
$.mobile.changePage( "#index2", { transition: "slide"} );
event.handled = true;
}
});
});
$("#list").listview('refresh');
});
});
$(document).on('pagebeforeshow', '#index2', function(){
$('#index2 [data-role="content"]').find('#deal-img').attr('src',dealObject.dealObject);
$('#index2 [data-role="content"]').find('#title').html(dealObject.name);
$('#index2 [data-role="content"]').find('input#desc').val(dealObject.description);
$('#index2 [data-role="content"]').find('input#tname').val(dealObject.dealName);
$('#index2 [data-role="content"]').find('input#dealid').val(dealObject.dealID);
});
var dealObject = {
dealID : null,
restaurantid : null,
shortName : null,
image : null,
dealName : null,
description: null
}
</script>
If somebody could help me I'd really appreciate it.
You will need to separate pages into two php files, one called view.php and second one called offer.php.
Create 2 additional directories, one called amend and second one called del. Both of them will have a js file with logic related to the amend or delete functionality plus a php file which will server as a php/ajax proxy for a needed functionality.
Also take care that your 2 ajax calls must look at a correct location and that ajax response also must state witch action has beed done.
My guess is that you will need to make an Ajax request to your server for index2.html, since it no longer lives on the same page as index1.html. Here's an example
$.ajax({
url : '/pages/index2.html',
type: 'get',
success: function (html) {
// here , you can use jquery to manipulate
// the HTML in index2. Maybe pop up a lightbox, etc..
}
});
I'm not sure what you're trying to do, but Ajax is a fairly standard way of requesting new HTML / data behind the scenes. There is a lot you can do with JQuery ajax. Here are the docs
Jquery Ajax
Background Info
I'm fiddling around with some PHP and AJAX at the moment, to try and get the code working for an auto refreshing div (every 10 seconds), that contains comments.
Here is javascript code I am using to refresh the div..
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#content_main').load('/feed_main.php');
}, 5000);
});
// ]]></script>
The code that will populate the div called "content_main", which is in feed_main.php, essentially accesses the database and echo's out the latest comments ...
Question
Is it possible, to only load the div "content_main" if the data inside of it, hasn't changed since the last time it was loaded?
My logic
Because I'm relatively new to javascript and AJAX I don't quite know how to do this, but my logic is:
For the first time it is run..
load data from feed_main.php file
Create a unique value (perhaps a hash value? ) to identify say 3 unique comments
Every other time it is run...
load the data from feed_main.php file
create a NEW unique value
check this value with the previous one
if they're the same, don't refresh the div, just leave things as they are, but if they're different then refresh..
The reason why I want to do this is because the comments usually have pictures attached, and it is quite annoying to see the image reload every time.
Any help with this would be greatly appreciated.
I've faced similar problem not too long ago, i assume that you using mysql or something for your comments storage serverside ?
I solved my problem by first adding timestamp integer column to my mysql table, then when i added a new row, i'd just simply use time() to save the current time.
mysql row insert example:
$query = "INSERT INTO comments (name, text, timestamp) VALUES ('". $name ."', '". $text ."',". time() .");";
step two would be to json_encode the data you sending from serverside:
$output = array();
if ($html && $html !== '') { // do we have any script output ?
$output['payload'] = $html; // your current script output would go in this variable
}
$output['time'] = time(); // so we know when did we last check for payload update
$json = json_encode($output, ((int)JSON_NUMERIC_CHECK)); // jsonify the array
echo $json; // send it to the client
So, now instead of pure html, your serverside script returns something like this:
{
"payload":"<div class=\"name\">Derpin<\/div><div class=\"msg\">Foo Bar!<\/div>",
"time":1354167493
}
You can grab the data in javascript simply enough:
<script type="text/javascript"> // <![CDATA[
var lastcheck;
var content_main = $('#content_main');
pollTimer = setInterval(function() {
updateJson();
}, 10000);
function updateJson() {
var request = '/feed_main.php?timestamp='+ (lastcheck ? lastcheck : 0);
$.ajax({
url: request,
dataType: 'json',
async: false,
cache: false,
success: function(result) {
if (result.payload) { // new data
lastcheck = result.time; // update stored timestamp
content_main.html(result.payload + content_main.html()); // update html element
} else { // no new data, update only timestamp
lastcheck = result.time;
}
}
});
}
// ]]> </script>
that pretty much takes care of communication between server and client, now you just query your database something like this:
$timestamp = 0;
$where = '';
if (isset($_GET['timestamp'])) {
$timestamp = your_arg_sanitizer($_GET['timestamp']);
}
if ($timestamp) {
$where = ' WHERE timestamp >= '.$timestamp;
}
$query = 'SELECT * FROM comments'. $where .' ORDER BY timestamp DESC;';
The timestamps get passed back and forth, client always sending the timestamp returned by the server in previous query.
Your server only sends comments that were submitted since you checked last time, and you can prepend them to the end of the html like i did. (warning: i have not added any kind of sanity control to that, your comments could get extremely long)
Since you poll for new data every 10 seconds you might want to consider sending pure data across the ajax call to save substantial chunk bandwidth (json string with just timestamp in it, is only around 20 bytes).
You can then use javascript to generate the html, it also has the advantage of offloading lot of the work from your server to the client :). You will also get much finer control over how many comments you want to display at once.
I've made some fairly large assumptions, you will have to modify the code to suit your needs. If you use my code, and your cat|computer|house happens to explode, you get to keep all the pieces :)
How about this:
<script type="text/javascript">
// <![CDATA[
$(function () {
function reload (elem, interval) {
var $elem = $(elem);
// grab the original html
var $original = $elem.html();
$.ajax({
cache : false,
url : '/feed_main.php',
type : 'get',
success : function (data) {
// compare the result to the original
if ($original == data) {
// just start the timer if the data is the same
setTimeout(function () {
reload(elem, interval)
}, interval);
return;
}
// or update the html with new data
$elem.html(data);
// and start the timer
setTimeout(function () {
reload(elem, interval)
}, interval);
}
});
}
// call it the first time
reload('#content_main', 10000);
});
// ]]>
</script>
This is just an idea to get you going it doesn't deal with errors or timeouts.
Best And Easy Code
setInterval(function()
{
$.ajax({
type:"post",
url:"uourpage.php",
datatype:"html",
success:function(data)
{
$("#div").html(data);
}
});
}, 5000);//time in milliseconds
how i can i change the content of a page without refreshing.I know we need to use hidden frames for this but all the tutorials i have come across teach this only for HTML files what if the content is returned from a PHP file how do i do it in such a case? what should the php file echo or return?
You will have to use Ajax for that, have a look at this tutorial:
AJAX Tutorial
If you use a hidden frame, the content won't be displayed (hence "hidden"), I think you just mean to use an iframe. But this doesn't fit your description of "without refreshing", since you have to refresh the frame.
When loading the PHP file inside the frame, your PHP file just needs to generate HTML the same way you would generate a normal page. It's the same whether the PHP file is loaded inside a frame or not.
I use this method for a lot of my websites and so does Google. If you want to get data from a PHP file and then dynamically update the page you need to "import" the PHP file somehow without the entire page being redirected, or using iframes (which works too but is a lot messier). The way you do this is to import the file as a "javascript" file.
The following code demonstrates a form called "testform" and a text input called "userpost".
When you submit the form, it will import a file, and then update div "outputText" with whatever you entered... and wait for it... all without the page being redirected at all or refreshed!
I have included a lot of extra functions to show how you can access all of your functions on the same DOM unlike if you use frames where you have to use "top.object" or what not
index.html
<html>
<head>
// Get objects by their id. We will use this in the PHP imported file
Get = function(id) {
return (!id) ? null : (typeof id == "object") ? id :
(document.getElementById) ? document.getElementById(id) :
(document.all) ? document.all[id] :
(document.layers) ? document.layers[id] : null;
}
// Formats a string so it does not break in a URL
String.prototype.formatForURL = function() {
var str = escape(this.replace(/ /gi, "%20"));
str = str.replace(/\&/gi, "%26").replace(/\=/gi, "%3D");
str = str.replace(/\//gi, "%2F")
return str;
}
String.prototype.contains = function(str) {
return (!str) ? false : (this.indexOf(str) > -1);
}
Object.prototype.killself = function() {
this.offsetParent.removeChild(this);
}
// Import the script
ImportScript = function(js) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("language", "JavaScript");
script.setAttribute("charset", "utf-8");
// we add the is tag so can delete the "js" file as soon as it executes
script.setAttribute("id", "import_" + head.children.length);
script.setAttribute("src", js + (js.contains("?") ? "" : "?") + "&is=" + head.children.length);
head.appendChild(script);
}
// Get and send value to php file
sendInfo = function() {
var file = "js/myFile.php?userpost=";
file += document.testform.userpost.value.formatForURL();
ImportScript(file);
}
</head>
<body>
<div>
<form name=testform onsubmit="sendInfo(); return false">
<input type=TEXT name=userpost />
<input type=SUBMIT value=Go />
</form>
</div>
<div id=ouputText>
This text will be replaced by what you type
and submit into the form above
</div>
</body>
<html>
js/myFile.php
<?php
// Here you can now use functions like mysql_connect() etc. even exec()
// ANYTHING! Save them into variables and output them as text which goes
// Straight into the javascript! e.g. :
// $con = mysql_connect("localhost", "username", "password");
// if($con) {
// ... code to retrieve data and save into $variable
// }
// print "alert(\"$variable\");"; // this alerts the value in variable
if(isset($_GET['userpost'])) {
$userpost = $_GET['userpost'];
?>
Get("outputText").innerHTML = "<?=$userpost; ?>";
<?php
}
?>
// Clear text area
document.testform.userpost.setAttribute("value", "");
// Remove the file from header after info is changed
Get("import_<?=$_GET['is']; ?>").killself();
If I had typed in "Hello World" into text input "userpost" then
div "outputText" would be filled with the words "Hello World"
deleting what was previously there, and the text input will be cleared
Hidden frames is one design pattern that is a part of the overall AJAX design pattern. This is an extreme high-level overview, but this is essentially how it works:
Javascript in your HTML page makes a request to your PHP script by using an XMLHTTPRequest object, or a hidden frame or iframe. This is usually done asynchronously, so you can continue to work with your HTML page while the request is being made.
The data is returned to your Javascript. At this point, you can then manipulate the page, and update data on the page using various DOM methods.