Javascript tips
Force a file download after an ajax request
January 26, 2013


Today I’d like to show you how to force the download of a file using an ajax request, since I think that this is a common problem. Because of the nature of ajax, it’s not possible to download a file during an asynchronous request. What can be done instead is using a combination of server/client side techniques to do this. First of all your async request must be handled by a server side script which creates and writes the file on a server and then returns back a json with the file path inside, something like this:

{"success":"true", "path":"path_to_my_file"}

At this point your ajax call could look like this:

	data: $('#my_form').serialize(),
	success: function(data){
			if (data.path !=''){
			var frame = $('<iframe>',{'src':data.path}).hide();


What happens here is that your backend script creates and saves the file where you need and should give you back the correct path using  Json. Now the function that handles the Ajax response creates an hidden iframe with its src attribute pointing to the file ( src=”path_to_my_file”) and appends it to the page body so that the browser will open the download window.

In this way you can  combine the nice-looking features of Ajax with a classic server side action like file downloading.






By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.