0

I have a php operation which sends a download count to a text file. With each file download, it increases the number.

The entire contents of the text file are like this:

39

As you see, there is nothing else in the text file. Just that number. With each new download, the number increases by 1. For example, say you go download the file, the number will change to 40.

I want to display this download number on a page. For example: Downloads: 39

The page I want to display on is php, so either php or javascript will work just fine. However, I prefer javascript.

The text file is on the same server in the same folder as the web page.

So, put simply, I want to read that value in the text file and display it on a web page.

3
  • 3
    You need an Ajax request. Commented Oct 20, 2013 at 1:37
  • you cannot access files stored on the server by using just Javascript. Commented Oct 20, 2013 at 1:37
  • If you don't have to update the number without reloading the page, just use php as both current answers suggest. But if you do, see this to get started with Ajax: developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest Commented Oct 20, 2013 at 1:43

2 Answers 2

4

Why not just include the file ?

Downloads: <?php include 'filename.txt'; ?>

See http://php.net/manual/en/function.include.php

Sign up to request clarification or add additional context in comments.

1 Comment

it worked great! but other guy also defined a variable which is what i needed! :) :) I voted you up though!
2

Just php:

   <?php
   $download_count = file_get_contents('file.txt');

   ?>
   Downloads: <?= $download_count ?>

Or to store it in a javascript variable.

  <script>
      var downloadCount = "<?= $download_count ?>";
  </script>

For Ajax:

PHP file:

<?php
echo file_get_contents('textfile.xt');

JavaScript: (using jQuery ajax)

$.get('/path/to/script.php').then(function(response) {
    $('#download-count').html(response);
});

HTML

Downloads: <span id="download-count"></span>

5 Comments

excellent!!! THank you, you defined a variable which is exactly what i need!! yay!!
I liked your additions, but can you tell me what file you're referring to for /path/to/script.php? THanks! Also do I need to include jquery? And do I need to include any other libraries?
Also is it possible to use the number in a javascript variable?
@Accelerator You don't need to include jQuery or any other library, but then you have to use the native XMLHttpRequest object. Working with an ajax wrapper is just a lot more convenient.
can you tell me what file you're referring to for /path/to/script.php?

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.