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:
$.ajax({ type:'get', dataType:'json', url:"my_url", data: $('#my_form').serialize(), success: function(data){ if (data.path !=''){ var frame = $('<iframe>',{'src':data.path}).hide(); $('body').append(frame); } } });
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.
Enjoy