PHPjQueryajax no-refreshing file download count statistics

Source: Internet
Author: User
This article is based on php + mysql + jquery ajax to achieve statistics on the number of downloads of refreshing files. if you need it, please refer to it. next I will introduce the implementation process step by step. This example requires the reader to have PHP, Mysql, jQuery...

This article is based on php + mysql + jquery ajax to achieve statistics on the number of downloads of refreshing files. if you need it, please refer to it. next I will introduce the implementation process step by step.

In this example, you need to have basic knowledge about PHP, Mysql, jQuery, html, css, and so on. before developing an example, you need to prepare a Mysql data table. In this example, assume that there is a downloads file download table, used to record the file name, the file name stored on the file server, and the number of downloads. The premise is that if data already exists in the download table, the data may be inserted when the file is uploaded in the background of the project, so that we can read the data on the page. The downloads table structure is as follows:

The code is as follows:

Create table if not exists 'downloads '(
'Id' int (6) unsigned not null AUTO_INCREMENT,
'Filename' varchar (50) not null,
'Savename' varchar (50) not null,
'Downloads' int (10) unsigned not null default '1 ',
Primary key ('id '),
Unique key 'filename' ('filename ')
) ENGINE = MyISAM default charset = utf8;

You can also directly download the Demo and import the SQL file. all the data is available.

HTML

We add the following HTML structure to the body of the index.html page, where ul. filelist is used to display the file list. now there is no content in it. we will use jQuery to asynchronously read the file list, so don't forget, we also need to load the jQuery library file in html.

The code is as follows:




CSS

To make the demo better display the page effect, we use CSS to modify the page. the following code mainly sets the display effect of the file list. of course, you can set the corresponding style as needed in the actual project.

The code is as follows:

# Demo {width: 728px; margin: 50px auto; padding: 10px; border: 1px solid # ddd; background-color: # eee ;}
Ul. filelist li {background: url (http://pic1.phprm.com/2013/05/02/bg_gradient.jpg) repeat-x center bottom # F5F5F5;
Border: 1px solid # ddd; border-top-color: # fff; list-style: none; position: relative ;}
Ul. filelist li. load {background: url (http://pic1.phprm.com/2013/05/02/ajax_load.jpg) no-repeat; padding-left: 20px;
Border: none; position: relative; left: 150px; top: 30px; width: 200px}
Ul. filelist li a {display: block; padding: 8px ;}
Ul. filelist li a: hover. download {display: block ;}
Span. download {background-color: #64b126; border: 1px solid #4e9416; color: white;
Display: none; font-size: 12px; padding: 2px 4px; position: absolute; right: 8px;
Text-decoration: none; text-shadow: 0 0 1px # 315d0d; top: 6px;
-Moz-border-radius: 3px;-webkit-border-radius: 3px; border-radius: 3px ;}
Span. downcount {color: #999; padding: 5px; position: absolute; margin-left: 10px; text-decoration: none ;}

PHP

The others page is called, and the other is download. php, which is used to respond to the download action, update the download times of the corresponding file, and complete the download through the browser. In fact, there is also a database connection file conn. php, which has been packaged in the download package. Click here to download.

Filelist. php reads the downloads table and outputs data in JSON format through json_encode (). This is prepared for the following Ajax asynchronous operations.

The code is as follows:

Require 'Conn. php'; // connect to the database
$ Result = mysql_query ("SELECT * FROM downloads ");
If (mysql_num_rows ($ result )){
While ($ row = mysql_fetch_assoc ($ result )){
$ Data [] = array (
'Id' => $ row ['id'],
'File' => $ row ['filename'],
'Downloads' => $ row ['downloads']
);
}
Echo json_encode ($ data );
}

Download. php transmits parameters based on the url to query the corresponding data and check whether the file to be downloaded exists. if so, the number of downloads of the corresponding data is updated + 1 and the header () is used () download. It is worth mentioning that the header () function is used to forcibly download an object, and you can set the name of the object to be downloaded and saved locally. In general, we use the background Upload program to rename the uploaded files and save them to the server. commonly, there are files named by date and time, one of these benefits is to avoid repeated file names and garbled Chinese names. To download a local file, you can use header ("Content-Disposition: attachment; filename =". $ filename) to set the file name to a name that is easy to recognize.

The code is as follows:

Require ('Conn. php'); // connect to the database
$ Id = (int) $ _ GET ['id'];

If (! Isset ($ id) | $ id = 0) die ('Parameter error! ');
$ Query = mysql_query ("select * from downloads where id = '$ ID '");
$ Row = mysql_fetch_array ($ query );
If (! $ Row) exit;
$ Filename = iconv ('utf-8', 'gbk', $ row ['filename']); // specify the conversion encoding for the Chinese name.
$ Savename = $ row ['savename']; // The name actually saved on the server
$ Myfile = 'File/'. $ savename;
If (file_exists ($ myfile) {// if the file exists
// Update the number of downloads
Mysql_query ("update downloads set downloads = downloads + 1 where id = '$ ID '");
// Download an object
Header ("Content-type: application/octet-stream ");
Header ("Content-Disposition: attachment; filename =". $ filename );
Exit;
} Else {
Echo 'file does not exist! ';
}

JQuery

JQuery on the front-end page mainly completes two tasks: reading the file list asynchronously through Ajax and displaying the file list; responding to the user click event, adding the corresponding file download times to 1. let's see the code:

The code is as follows:

$ (Function (){
$. Ajax ({// asynchronous request
Type: 'GET ',
Url: 'filelist. php ',
DataType: 'json ',
Cache: false,
BeforeSend: function (){
$ (". Filelist" pai.html ("

  • Loading...
  • ");
    },
    Success: function (json ){
    If (json ){
    Var li = '';
    $. Each (json, function (index, array ){
    Li = li +'
  • '+ Array ['file'] +
    ''+ Array ['downloads'] +'
    Click to download
  • ';
    });
    $ (". Filelist" ).html (li );
    }
    }
    });
    $ ('Ul. filelist a'). live ('click', function (){
    Var count = $ ('. downcount', this );
    Count. text (parseInt (count. text () + 1); // number of downloads + 1
    });
    });

    First, after the page is loaded, use $. ajax () to the background filelist. php sends a GET Ajax request when filelist. after php succeeds, it receives the returned json data through $. each () traverses json data objects, constructs html strings, and adds the final strings to ul. the file list in the demo is formed in filelist.

    Then, when you click to download an object, you can use live () to respond to the click event of the dynamically added list element and accumulate the download count.



    Address:

    Reprinted at will, but please attach the article address :-)

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.