0

i have a php script that counts button clicks to a txt file. this is working just fine.
On my html page i am displaying the clicks as such :

<?php
include ('counter.php');
?>
<div class="count_right" id="one"></div>
<div class="count_left" id="two"></div>
<form action="" method="post" id="form" >
<button class="vote_right"  name="clicks1" ></button>
</form>
<form action="" method="post" id="form2"  >
<button class="vote_left"  name="clicks2"></button>
</form>

the php

<?php
if( isset($_POST['clicks1']) ) { 
incrementClickCount1();
}

function getClickCount1()
{
return (int)file_get_contents("count_files/clickcount1.txt");
}

function incrementClickCount1()
{
$count = getClickCount1() + 1;
file_put_contents("count_files/clickcount1.txt", $count);
}


if( isset($_POST['clicks2']) ) { 
incrementClickCount2();
}

function getClickCount2()
{
return (int)file_get_contents("count_files/clickcount2.txt");
}

function incrementClickCount2()
{
$count2 = getClickCount2() + 1;
file_put_contents("count_files/clickcount2.txt", $count2);
}
?>

and the js (EDITED)

<script type="text/javascript">
var valueOne = "<?php echo getClickCount1(); ?>";
var valueTwo = "<?php echo getClickCount2(); ?>"; 
 $('#one').html(valueOne);
 $('#two').html(valueTwo);
 $('.vote_right').click(function(){

$.ajax({
 type: "POST",
 url: "counter.php",
 data: valueOne,
 cache: false,

 success: function(data)
 {
 $("#one").html(data);

 }  });                         

 </script>

tried also adding

e.preventDefault();

but then the button wont work. My problam is that i dont want the page to refresh when the button is clicked. insted i would like the div to refresh with the new data.
I have tried usin ajax but with no success. its either the page refreshes or the data wont update.
Any suggestions?

fafchook
  • 717
  • 1
  • 9
  • 16
  • 3
    AJAX + JSON is your answer. It's well documented in the jQuery docs and Google is overflown with examples of it. –  Dec 26 '13 at 19:22
  • Also, for your `action=''` attribute, you should omit it all together if it is just empty, see here: http://stackoverflow.com/questions/1131781/is-it-a-good-practice-to-use-an-empty-url-for-a-html-forms-action-attribute-a – Arian Faurtosh Dec 26 '13 at 19:27

3 Answers3

0

Use type=button to not submit the form when clicking buttons (and thus prevent page reloading).

<button type="button" class="vote_right" name="clicks1" ></button>
Stephane Lallemagne
  • 1,216
  • 11
  • 18
0

The below shows how to write two of the 4 api calls you need to add to your website.

Main Page:

<?php
    include ('counter.php');
?>
<div class="count_right" id="one"></div>
<div class="count_left" id="two"></div>
<button class="vote_right"  name="clicks1" onclick="addCount1()"></button>
<button class="vote_left"  name="clicks2" onclick="addCount2()"></button>

JS:

<script type="text/javascript">
    var valueOne = //use ajax (GET) to call the page for count1;
    var valueTwo = //use ajax (GET) to call the page for count2;

    $(document).ready(function(){
        $('#one').html(valueOne);
        $('#two').html(valueTwo);
    });

    function addCount1(){
        //use ajax (POST/PUT) to call a page that adds 1 to your text file thing for count1
    }

    function addCount2(){
        //use ajax (POST/PUT) to call a page that adds 1 to your text file thing for count2
    }
</script>

New API Page (for count1):

<?php
    class IntegerValue implements JsonSerializable {
        public function __construct($number) {
            $this->number = (integer) $number;
        }

        public function jsonSerialize() {
            return $this->number;
        }
    }

    echo json_encode(new IntegerValue(getClickCount1()), JSON_PRETTY_PRINT);
?>

New API page (for count2):

<?php
    class IntegerValue implements JsonSerializable {
        public function __construct($number) {
            $this->number = (integer) $number;
        }

        public function jsonSerialize() {
            return $this->number;
        }
    }

    echo json_encode(new IntegerValue(getClickCount2()), JSON_PRETTY_PRINT);
?>

How PHP and JavaScript work

On initial page load: The process flow looks like this:

Server Side code (php) -> sends data to client -> browser begins rendering and executing JS

On form Submit:

Client Executes code (javascript) -> Sends data to server -> Server gets data and processes (PHP)

Because of this if you don't want the page to "refresh" you'd have to use JavaScript and the best way of handling this is AJAX if you use a form you are going to get a refresh also known as a POST-BACK. Otherwise with AJAX you can easily just send a POST or a GET and it won't refresh.

abc123
  • 16,261
  • 6
  • 46
  • 76
  • thanks. dont know anything about json but i will sure give it a try. however it brings out this error when i try to place the ner php code
    Fatal error: Interface 'JsonSerializable' not found
    – fafchook Dec 26 '13 at 19:40
  • @fafchook http://www.php.net/manual/en/jsonserializable.jsonserialize.php `(PHP 5 >= 5.4.0) JsonSerializable::jsonSerialize — Specify data which should be serialized to JSON` – abc123 Dec 26 '13 at 19:55
  • my xampp version was outdated. anyhow, i've tried youe method for hours but nothing seems to work. probebly because i dont know the right way to call the data by ajax. i cant get the value to show via GET only by and i cant get the counter to work on clicking. i would greatly appreciate any help.. – fafchook Dec 27 '13 at 07:51
  • @fafchook added more details, I can show you more info. First, install RestConsole in Chrome. Then use it to call your rest service you made, this will show you what JSON is returning. Otherwise, we can discuss this on any medium. The "answer" to this question is difficult though since you are really needing assistance understanding PHP/Ajax not really just a quick fix. Let me know if you'd like to go into this further. – abc123 Dec 28 '13 at 07:45
  • @fafchook here is another answer I gave to someone http://stackoverflow.com/questions/16323360/submitting-html-form-using-jquery-ajax/16324058#16324058 – abc123 Jan 03 '14 at 18:31
0

No need to put with in form tag for ajax async request.

Use only

<?php
include ('counter.php');
?>
<div class="count_right" id="one"></div>
<div class="count_left" id="two"></div>
<button class="vote_right"  name="clicks1" ></button>
<button class="vote_left"  name="clicks2"></button>