문제

I want to make a website where there is a button, and when you click it make it change some text (saying either true/false). The text must change when the user clicks the button, but not just for the one user, for every user that's on the site.

The way I'm trying to do it is I have a text file, and so far all I've got is some text on the page that every 500 milliseconds is refreshing to display whatever is in the text file.

So now all I need to do is update the text file when the button is clicked. What's the best way I could do this? (I want to be able to press the button on the computer hosting the site OR another computer accessing the site.)

Thanks, Fjpackard.


Update

index.php:

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

<body>

<div id="theDiv"></div>

</body>

<script>

$("document").ready(function(){
    $("button").remove();
    setInterval(function(){
         $("#theDiv").load("file.txt");
    },500);
    var deviceAgent = navigator.userAgent.toLowerCase();
    var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
    if (agentID) {

        // mobile code here

    }
    else {
        $("body").prepend("<button>Toggle</button>");
        $("#theDiv").css("visibility","none");

        $("button").click(function(){
            myClick();
        });
    }
});

function myClick() {
                var url = ''; //put the url for the php
                value = $.post("", {}).done(
                    function(data) {
                        $('#theDiv').html(data);
                    }
                );
            }

</script>

script.php:

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        $file = 'file.txt';

        $previous = file_get_contents($file);
        if ($previous === 'true')
        {
            file_put_contents($file, 'false');
            echo 'false'; //this is what we return to the client
        }
        else
        {
            file_put_contents($file, 'true');
            echo 'true'; //this is what we return to the client
        }
        exit();
    }
?>
도움이 되었습니까?

해결책 2

You will be reading a file on the server with the name "file.txt".

Let's say you have this code to refresh the page each 500 milliseconds:

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
    function myClick()
    {
        //somehow get and change the value
        /*var value = ???*/
        $('#theDiv').html(value ? 'true' : 'false');
    }

    $("document").ready(
        function()
        {
            setInterval(
                function()
                {
                    $("#theDiv").load("file.txt");
                },
                500
            );
        }
    );
</script>
<div id="theDiv"></div>
<input type="button" value="click me" onclick="myClick()">

So now all I need to do is update the text file when the button is clicked. What's the best way I could do this? (I want to be able to press the button on the computer hosting the site OR another computer accessing the site.)

script.php:

<?php
    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        $file = 'file.txt';

        $previous = file_get_contents($file);
        if ($previous === 'true')
        {
            file_put_contents($file, 'false');
        }
        else
        {
            file_put_contents($file, 'true');
        }
        exit();
    }
?>

This is the server side code that updates the file.

index.php

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
    function myClick()
    {
        var url = 'script.php'; //put the url for the php
        $.post(url, {}); //avoiding using "done", let the timer update instead
    }

    $("document").ready(
        function()
        {
            setInterval(
                function()
                {
                    $("#theDiv").load("file.txt");
                },
                500
            );
        }
    );
</script>
<div id="theDiv"></div>
<input type="button" value="click me" onclick="myClick()">

And here we are making an ajax request to execute that code from the event handler of the button.

Note: the code $.post(url, {}) will make the request. In this case we are not using the done continuation (that would be executed when the server sends its response) to avoid a race condition with the timer.


So far you have been reading file.txt. You could take advantage of script.php to provide the current value. That will be done in a GET request instead of a POST.

script.php:

<?php
    // disable cache by HTTP
    header("Expires: Thu, 01 Jan 1970 00:00:00 GMT");
    header('Cache-Control: max-age=0, no-cache, no-store, must-revalidate');
    // disable cache by IE cache extensions
    header('Cache-Control: post-check=0, pre-check=0', false);
    // disable cache by Proxies
    header("Pragma: no-cache");

    $file = 'file.txt';

    if ($_SERVER['REQUEST_METHOD'] === 'POST')
    {
        // POST request

        $previous = file_get_contents($file);
        if ($previous === 'true')
        {
            file_put_contents($file, 'false');
        }
        else
        {
            file_put_contents($file, 'true');
        }
    }
    else
    {
        // not POST request, we assume it's GET

        echo file_get_contents($file);
    }
    exit();
?>

index.php:

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
    function myClick()
    {
        var url = 'script.php'; //put the url for the php
        $.post(url, {});
    }

    $("document").ready(
        function()
        {
            setInterval(
                function()
                {
                    $("#theDiv").load('script.php');
                },
                500
            );
        }
    );
</script>
<div id="theDiv"></div>
<input type="button" value="click me" onclick="myClick()">

As you can see, we are now using script.php both to read and to write. This facilitates doing checks on the server. For example: maybe not all users are allowed to update the value or to retrieve it.

Note: There is a race condition on the saver. If two clients makes requests on the server "at the same time" their updates on the file will overlap and the result will look like only one update happened (instead of two).


Observations:

  1. You may want to do additional checks on the server, for example verify the user session. Maybe not everybody is able to update the state.
  2. If you want to do more operation on the same PHP code, you may want to send variables on the POST request. In this case we are not doing that (we just send {}).

Also consider:

  1. Using Web Sockets that provide a more versatile mechanism to push notification to the clients. There are some libraries for this, see the question Is native PHP support for Web Sockets available? where some alternatives are pressented.
  2. Using an storage format (such as ini, json, xml...) that will provide your the ability to store more info in the same file.
  3. Using a database for storage. Databases will solve the race condition on the server, and provide means to store more complex data. The database engine doesn't need to be MySQL... in fact, for this use a document based database may be better idea (most of them often refered as NoSQL, although some of them actually support SQL).

다른 팁

Onclick of that button make one Ajax request using jQuery or simple javascript. Which will update that text file.

How to make Ajax request in jQuery: http://api.jquery.com/jquery.ajax

Iinjoy

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top