Clickable html button counter using php or js - javascript

I am very new to php and javascript and I was wondering how I could make a global counter that adds 1 to it every time a user presses a button. The number would stay the same even if someone is on a different computer or refreshes the page. I had this using javascript:
<script type="text/javascript">
var clicks = 0
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onClick="onClick()">Click me</button>
<footer>Clicks: <a id="clicks">0</a></footer>
But when ever someone refreshes the page, it resets the number, and it is not global. I tried making something in php which is:
<?php
$clicks = 0
public function clickButton()
{
$clicks = $clicks + 1
}
?>
but I have no idea what I'm doing and how to call the php function or display the php variable.

Your current problem is that your Click variable is only storred on the one computer clicking.
You need to do 2 things:
Store the click variable.
Read the click variable.
(Live updates.)
Store the click variable:
As Vinicius Maia said you need a connection between the users and this can be done with a database, read about MySQL.
Or you can use a more simple method and use php to read and create / write the Click variable into a file named Clicks.txt. See PHP Filesystem Functions on W3C
Read the click variable:
If you chose the MySQL method you should use the commands as so, else if you chose the primitive method you can use the following command: Php File Get Content
Live updates:
To show the variable live and not making your users refresh you should be able to use AJAX so make sure to take a look at that. This question might be usefull.
You should make a interval loop which should constantly check for updates in the variable. This question might be usefull
Together:
Take a good look at Jonas w's answer, he gives a good example on how you could make this and he follows your request. Only downside by using this tactic is that everytime you click you refresh, which might be annoying for some users.
But what he does is:
He reads the variable.
When you click the button he runs the PHP code by opening it.
When done with the code he send you back to index and refresh the side
Repeat...
But for your users, maybe you should add the live function by using this system:
Read the variable.
Make a loop with AJAX that calls a php function that checks and return updates
When you click the button use AJAX to run another php function to update the variable
Repeat...

You have the right JavaScript logic, now you just need to store your clicks somewhere that won't be affected by a browser refresh!
My first suggestion would be to utilize HTML5's localStorage object.
The examples are pretty good on the link. See if you can make something work!

Javascript or PHP will not solve your problem. Just because what you need is some connection between all users that will access your website. For that, you must use some kind of database. I recommend you starting learning MySQL.
Check this: http://php.net/manual/en/book.mysqli.php

The php variables just work inside of one request. So if two people request your site, the script runs twice in two different versions. You have to store the variable on the server.
You could store it into a mysql database ( good articles about that on php.net)
or you could make a counter.txt and edit it with php. ("Fopen" on php.net)
The php runs on the server and cannot interact with the clients side js. You need to send this "button click" to the server. You can do this with AJAX ( google that) or reloading the site and passing gets and posts to the server
Update.php:
<?php
$file=fopen("counter.txt","c+");//open or create counter.txt
$counter=fread($file, 10);//read content
$counter=(int)$counter+1;//add one
fwrite($file,$counter);//save counter
fclose($file);//close file
Header("Location: index.php");//go back to index.php
?>
Index.php:
<?php
$file=fopen("counter.txt","c+");
$counter=fread($file, 10);
fclose($file);
Echo $counter;
?>
Click me

if you need that different users see the same counter, then you will need save the counter in a database.
Regards.

Related

repopulating $_POST variables transparently in PHP

So.
In a LAMP stack (PHP), I've got this situation where I'm showing an intermediate page based on some variable from the first page --more simply, I have one page called, say, ListOfProjects, from which I can select a project to view.
When I go to that project, there are other page-navigation elements (like looking at individual jobs in the project, say) the user can click. Once I click them, and am navigated away from the intermediate page between ListOfProjects and IndividualJob, I have to resubmit the data that got me there.
That's fine, and if I could do it automatically, I would. However, I haven't found a way to force this behavior and eliminate the extra click and the ugly "Confirm Form Resubmission" screen.
Does anyone know a way I could A) silently force form-resubmission when the user hits the back button or B) avoid the situation where there's a form that needs resubmitting?
I've thought about trying to just pass that project ID to the session variable, but it's well within scope to have more than one individual project open in the same browser, which would make that unwieldy.
Thoughts? Suggestions?
Thanks!
Don't use POST.
When you are getting data from the server, use GET and put the data in the query string.
POST is designed for sending data to the server that will make a change (e.g. updating data in the database), it isn't appropriate for just deciding what data to look at.
Some solution is bypass using jQuery to resubmit a form when click on back:
<?php if (isset($_POST['ListOfProject'])): ?>
<form method="POST" id="backToProject"></form>
<script>$("#backToProject").submit()</script>
<?php endif ?>
Another solution is to use header("Location: ...") to force users to redirect a page, BUT you should remove all previous $_POST request using unset($_POST) such as:
unset($_POST);
header("Location: your_uri://your_path");
Try reload a page and reload a page using javascript into <script> tag such as:
if ($_POST['ListOfProject'])
{
echo '<script type="text/javascript">location.reload();</script>';
}
Try to understand GET/POST method: https://en.wikipedia.org/wiki/Post/Redirect/Get
And I don't recommended using link of sites using $_POST method such as say Quentin user.

how to update content automatically without reloading webpage using php/ajax?

I'm trying to create an auction tool using PHP. The problem I'm having (and I appreciate its a basic one but I need clarification) is that I don't understand how to update the "auction price" automatically on each users screen without them having to take any action or without causing a full reload of the page.
So far I understand that Ajax is used to do this but if anyone could point me in the right direction or to any useful materials. My plan for my project so far is to use PHP and JavaScript so any solution would need to be compatible with these languages.
Note: I'm using a MySQL database.
Ther question you asked has so much possible answers, they could fill a whole book.
The simplest way to do this is to make an ajax call every few seconds using a combination of the setInterval() function and AJAX calls. You basically make an AJAX request every few seconds:
setInterval(function(){
$.get( "anyChanges.php", function( data ) {
//do something with the returned data. Maybe update a table or something
});
}, 3000);
On server side anyChanges.php returns some data immediately, like confirmation that something has changed and the new data.
Long polling is how Google and others do it. It's the same as the example above. The difference is on the server side. anyChanges.php would not return immediately, the script would keep the connection open until there is some new changes and return them. If you use long polling, you usually set the interval to longer, for example 30 seconds.
The best way to do it in my opinion, are WEB Sockets. It is a very new technology. With web sockets you can create a two-way connection to the server. That means that the server could simply send data to the clients without them having to ask for new data every few seconds. In PHP it's a little difficult to use web sockets (Or so I heard), but you could give it a shot. If you choose web sockets, try to learn about them first:
tutsplus tutorial
This library will be helpfull:
socketo.me
Php/Ajax example:
In this example you have index.html and record_count.php files
Here is the Code:
index.html contains the html code and javascript call to load record_count.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('record_count.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
<body>
<div id="load_tweets"> </div>
</body>
and record_count.php has the php code
<?php
echo "some code or variable here";
?>
you can change the javascript interval to suit your needs
I'll leave you the blog link as a reference: 9lessons
As I making interactive displays, which must switch pages instantly, then I create pages without refreshing.
My approach is something like that:
I have one index.html with all structure (pages) with all necessary html tags.
javascript/typescript loads json from CMS (Kirby for example), which has all information about texts and image links.
when json is loaded now I just need to switch between pages by showing/hiding or creating/removing html elements. And all data and texts are loaded by javascript.
There is some cons, which can be fixed, for example link for each page in address bar. In that case You need to add history management and change url in address bar on page switch.

How to set a PHP object in session upon a hyperlink click

I have two PHP pages: One displays the information about an object retrieved from MySQL database and the other allows the user to edit it. The user is transferred from the first page (the view page) to the edit page upon clicking a hyperlink.
I would like to set the information retrieved from the database in session before passing on to the edit page so as to avoid an extra database call. How can I set an object in session upon a hyperlink click event? I know I could append the object as a variable to the GET request but is there a cleaner way than that?
Put the object into the session ($_SESSION['object'] = $object) when the page one loads (or when you retrieve the object from the database). This way you avoid a second call to the database. If you want to place it into the session upon the click event, a second call would be necessary, since you would have to make an AJAX call to a PHP script that retrieves the object. However, this may only make sense if the user is expected to edit that information, otherwise it is just storing data into sessions for no reason, which may also expose security bugs. If your database call doesn't retrieve millions of records, or you don't have hundreds of millions of users editing data in the same time, I can assure you that the impact on the performance by making a second call will go unnoticed.
Adding an object to the session:
$_SESSION['the_object'] = $object;
(Disclaimer: Will not work if the object contains any non-serializable components like closures)
Now when to do it? Actually, you have to do it on the page that shows the data, because if you do it later when the user clicks the edit link, this already triggers a new request which then would again go to the database - you'd have two requests (one for the list, one for the edit).
Generally, the edit link has the ID of the database entry to be edited. But pay attention to carefully check whether the user is allowed to have access or not, because MySQL will simply increment the ID, so it's easy to guess which IDs are valid. Anyone with a tiny bit of clue can modify a HTML form to tamper with IDs.
The approach with the session is somewhat easier: You only allow to edit what has been stored in the session, so the access control has to be done on the list page only.
For those who may be looking for a code snippet to help do this - here it is
Page 1 - this page just loads data from a DB and displays it in a non-editable mode on the screen. On this page we need an Javascript function that can be activated when the hyperlink is clicked
<script language="JavaScript" type="text/javascript">
function processEditLink(){
$.post('process_session_put.php', <?php echo "{S-Object:'".json_encode($obj_)."'});"; ?>
window.location.href = 'edit_object.php';
}
</script>
To explain the above code - we are taking an object (referred to as obj_) and encoding it into the JSON version by using the inbuilt function json_encode. Remember to ensure your object implements JsonSerializable in order to accomplish this. After that we are passing that JSON string as a POST URI parameter via AJAX to a secret page called process_session_put.php. This call is never visible to the end user and happens secretly when the hyperlink is clicked. The secret PHP page will decode the JSON string back into the PHP object and put it in session for all to use. Finally, once that function is complete, the window redirects to the actual edit page that can access data from session and populate the screen.
Next we should modify the hyperlink to trigger this Javascript function when it is clicked as below
<a class="edit-link" href="javascript:processEditLink(this);return false;">[Edit]</a>
Finally - the PHP page called process_session_put.php - which actually does the background work of decoding the JSON string passed to it back into the object format and putting it in session
<?php
if (!isset($_SESSION))
{
session_start();
}
// OBTAIN THE JSON STRING FROM POST URL, DECODE IT AND PUT IT BACK AS A OBJECT IN SESSION
$_SESSION["E-Object"] = json_decode($_POST["S-Object"]);
?>

Multiple types of MySQL query within same page

As I was learning PHP I used forms and posts across multiple pages, for example: a form on addpage.php would point to another page which would execute MySQL code using the post values from addpage as variables.
This served me well for making the code work, but now I have implemented the code all within the same page using if(isset($_POST['submit'])) then running the SQL code.
On my pages which display database info, I have javascript buttons which currently direct the user to various pages and append a $_GET on to the url with the id of the row. an example of this is:
function deleteRow(id) {
var r=confirm("Are you sure you want to delete this row?")
if (r==true)
{
location.href = "deleterow.php?id=" + id;
}
}
deleterow.php simply grabs the $id = $_GET['id'] and runs a delete query with a WHERE id = $id. Not the most elegant solution but it works. (NB. this isnt the actual code i used, just saved time writing this way)
If the buttons were forms rather than javascript buttons I know that I could give the submit buttons specific names e.g. if(isset($_POST['delete'])) { run delete code.. but this would cause layout issues.
What I want to know is, if there is method for integrating this into a page, rather than having a seperate PHP page for deleting and things? My current method works fine for the purpose, but in the interests of learning i'd like to keep the number of pages in the site to a minimum, without pages with just one block of code in them with redirects.

Setting the session on click of a button

I want to set a session variable on click of a Button. But without clicking that button the session variable is set.
What is wrong in my code? Please help..!!
My script is -
<script>
$(document).ready(function(){
$("#next").click(function(){
<? $_SESSION["s_id"]=mt_rand(); ?>
location.reload();
});
});
</script>
PHP gets executed before you see the site. If this js gets rendered, php is already done with its work and wont do any more. If you want to set a session with a click on a div, you have to create a form and use $_POST to send the request back to the server.
Remember: You can NEVER execute php code like this in javascript. javascript is clientside, while php is serverside.
Session variables need to be set before a document outputs any data. You could possibly use an AJAX call to allow the session to be set in an external file on button press.

Categories

Resources