Two quick tips for image refreshing and download dialogue

As we are moving to use more and more "AJAX" on pothi.com, I keep learning new things everyday some of which really entertain me :-). So let me put them down here.

  • How to make sure that an image refreshes from server and not from cache?

    Suppose you have an img tag and the file in its src attribute is being updated on the server through a ajax call. Now we have to make sure that when the src file changes, the image on the page is also refreshed. On its own, the browser will simply use the version of the file in the cache. To avoid that, you can simply attach a GET query to the end of the image url. So src="test.png" becomes something like - src="test.png?random=<any randomly generated string>". For the random string you can use the surrent time stamp. Short and sweet :-)
  • How to show a download dialogue for files that browser usually opens without asking?

    Browsers usually have a mapping of MIME types and applications. If they get data of a particular mime type and know how to handle that, they will open it i.e. pdf files. In order to force the browser to show a download dialogue which gives an option of either opening or saving, you have to send a header something like this - 'Content-Disposition: attachment;filename="test.jpeg"' . This can be done in php using the header function. A more detailed article is on apptools - http://apptools.com/phptools/force-download.php

These are small things with quick solutions but can sometimes prove to be the final stumbling blocks. I hope somebody will find it useful.

Comments

Piyush said…
In fact same thing is used elsewhere for good caching. Put svn revision number on js and css file names making sure these files get cached until they are actually changed.

Popular posts from this blog

बिछड़ते दोस्तों के नाम

क्या लिखूं?

Do nightmares qualify for dreams?