Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

php - Update text file on button click

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();
    }
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...