views:

6729

answers:

5

Hello all,

How can I prompt a download for a user when they click a link.

For example, instead of:

<a href="uploads/file.doc">Download Here</a>

I could use:

<a href="#">Download Here</a>

 $('a').click... //Some jquery to download the file

This way, Google does not index my HREF's and private files.

Can this be done with jQuery, if so, how? Or should this be done with PHP or something instead?

Thanks!

+1  A: 

Yes, you would have to change the window.location.href to the url of the file you would want to download.

window.location.href = 'http://www.com/path/to/file';
MacAnthony
+7  A: 

I might suggest this, as a more gracefully degrading solution, using preventDefault:

$('a').click(function(e) {
    e.preventDefault();  //stop the browser from following
    window.location.href = 'uploads/file.doc';
});

<a href="no-script.html">Download now!</a>

Even if there's no Javascript, at least this way the user will get some feedback.

karim79
jQuery is **the** answer.
voyager
Thanks, this is what I was looking for. I usually use "preventDefault", just left it out above because I was being lazy. ;-)
Dodinas
Thanks! What I was looking for as well!
Markos Fragkakis
+8  A: 

If you don't want search engines to index certain files, you can use robots.txt to tell web spiders not to access certain parts of your website.

If you rely only on javascript, then some users who browse without it won't be able to click your links.

Rob
Good to know about the 'robots.txt'. Thank you.
Dodinas
+3  A: 

Here's a nice article that shows many ways of hiding files from search engines:

http://www.antezeta.com/blog/avoid-search-engine-indexing

JavaScript isn't a good way not to index a page; it won't prevent users from linking directly to your files (and thus revealing it to crawlers), and as Rob mentioned, wouldn't work for all users.
An easy fix is to add the rel="nofollow" attribute, though again, it's not complete without robots.txt.

<a href="uploads/file.doc" rel="nofollow">Download Here</a>
Kobi
+1 For the Helpful Link, Thanks.
Dodinas
A: 

Hidden iframes can help

letronje