Hello there , currently am working on download site that contain items , I need to place download hits for every file in site, I used the old way that open popup php page and increase the counter then store the result in database, its not cool to do this, so I want to make this works with ajax , the user just click download and start downloading without any popups, what should I do ?
Example with code will be helpful, Thanks.

Recommended Answers

All 6 Replies

For download files not necessarily to use AJAX.
You can this does without use AJAX.

<a href="download.php?file_id=123456" target="_blank">Download File</a>

download.php

//execute any actions
//get $file_name by file_id

if(file_exists($file_name))
        {
            $ext = pathinfo($file_name, PATHINFO_EXTENSION);
            switch($ext)
            {
              case "pdf": $ctype="application/pdf"; break;
              case "zip": $ctype="application/zip"; break;
              case "doc": $ctype="application/msword"; break;
              case "xls": $ctype="application/vnd.ms-excel"; break;
              case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
              case "mp3": $ctype="audio/mp3"; break;
              case "gif": $ctype="image/gif"; break;
              case "png": $ctype="image/png"; break;  
              case "jpeg":
              case "jpg": $ctype="image/jpg"; break;
              default: $ctype="application/force-download";
            }

            header('Content-Description: File Transfer');
            header('Content-Type: '.$ctype);
            header('Content-Disposition: attachment; filename="'.rawurldecode($file_name).'"');
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: private');
            header('Pragma: private');
            header('Content-Length: '.filesize($file_name));
            readfile($file_name);
        }
        else 
        {
            echo 'File Not FOUND';
        }
commented: I was need for Ajax just for not to relode page, but this code may come in handy someday , thanks +0

When you click the button you could create a iFrame with Javascript and display:none; in css, that would download right on the page.

commented: Thats what i was looking for +0

After click by the button you not transition to a new page, and begin download file.

Just click on a thump and downloding start .

Thanks guys for the help, I used hidden Iframe to solve my problem

    <a href="download.php?file_id=<? echo $data['id']; ?>" target="hideframe">
    <iframe name="hideframe" src="" width="0" height="0" class="hidden"></iframe>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.