I am trying to have a button that can be clicked and will then display the number of times it has been clicked. I want the variable, let's call it x, to be stored online, so that if one person clicks the button 5 times and then another person later clicks it an additional 3 times each screen will then display x as 8. I attempted local storage but that only stores the variable on the browser. I have been doing some research and it seems like I will have to store x on a file and then access it with an XMLHttpRequest. I am very new at Javascript and am not sure how to do this. Could someone please respond with code that would achieve this and an explanation of what I will have to do to store the variable?
For the Javascript side of it, you can use jQuery to make things a little easier
$(document).ready(function() { /* perform AJAX XMLHttpRequest */ $.get("/click_count.php", function(data) { /* write the response into the HTML document */ $("#click_count").text(data); }); }); function save_click() { /* perform AJAX XMLHttpRequest */ $.post("/save_click.php", function(data) { /* write the result to the HTML document */ $("#click_count").text(data); }); }
<!-- include jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <body> <button onClick="save_click();">click me!</button> Button has been clicked: <span id="click_count">0</span> times! </body> </html>
Finally, you need to have two files (or one that does two things) which take advantage of a server-side technology.
The way the Server-side code works is like this:
The clicks are stored in a file called click_count.data
whenever anybody visits the file click_count.php , it simply reads the click_count.data file and sends whatevers in it as the response.
Then, there's another file called save_click.php , which takes whatever is in click_count.data and then increases it by one before sending it back.
The Javascript AJAX requests use these two files to save data on the server rather than on a per-client basis.
For server-side, I've chosen to use PHP
File: click_count.php
<?php
/* print out the contents of the file 'click_count.data' */
print_r(file_get_contents("click_count.data"));
?>
File: save_click.php
<?php
/* grab the current click count from click_count.data */
$click_count = intval(file_get_contents("click_count.data"));
/* increase it by 1 */
$click_count++;
/* write the new value into the file */
file_put_contents("click_count.data", $click_count);
/* print out new click count */
print_r($click_count);
?>
Last file: click_count.data
0
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.