0

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.

Edited by OsaMasw

4
Contributors
6
Replies
8
Views
4 Years
Discussion Span
Last Post by OsaMasw
1

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';
        }

Edited by radow

Votes + Comments
I was need for Ajax just for not to relode page, but this code may come in handy someday , thanks
2

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

Votes + Comments
Thats what i was looking for
0

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

Edited by radow

0

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>
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.