1

I'm making a webpage that (mostly) lets users increment a counter. I can read the file with jQuery .load() just fine, but writing to it is proving difficult.

Relevant code:

HTML

  <button onclick="add();">increment</button>
  <p>counter value: <span id="c"></span></p>
  <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
  <script>
    $(function() {
      $("#c").load("c.txt");
    });
    function add() {
      $.get("add.php");
      $("#c").load("c.txt");
    }
  </script>

add.php

<?php
  $file = fopen("c.txt", "w");
  $c = fread($file, filesize("c.txt"));
  fwrite($file, (int)$c + 1);
  fclose($file);
?>

c.txt
0 or 47 or your favorite positive integer

I'm not sure what I'm doing wrong here.

2 Answers 2

1

the problem is you are trying to call an async function as not sync behavior. So you must change the add method to call $.get and use the callback response from the server to load your file again example:

function add() {
      $.get("add.php", function (dataFromTheServer) {
      $("#c").load("c.txt");
    });     
}

A better alternative is to receive the count directly from the serve so you don't have to do another request to update the count example:

HTML

<button onclick="add();">increment</button>
  <p>counter value: <span id="c"></span></p>
  <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
  <script>
    $(function() {
      $("#c").load("c.txt");
    });
    function add() {
      $.get("add.php", function (data) {
       $("#c").text(data);
    });
      
    }
  </script>

also, you have to open the file to read and write using w+ PHP: add.php

<?php
  $file = fopen("c.txt", "w+");
  $c = fread($file, filesize("c.txt"));
  fwrite($file, (int)$c + 1);
  fclose($file);
echo $c;
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Tried this and it just outputted the php file (and didn't write to c.txt)
0

I would solve the add.php this way:

<?php
  $c = file_get_contents("c.txt");
  file_put_contents("c.txt", (int)$c+1);
?>

Adopted from the exmaple here: https://www.php.net/manual/en/function.file-put-contents.php

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.