«

»

Feb 07

Updated script for downloading file from javascript

I had to use the ajax to download a file internally on our NestForms project. I was searching for a solution and found one on Filamentgroup website.

Unforutunatelly, there were some issues that it did not correctly encoded the request. So I had to update the script in order to make it working. See the code below. I hope that it will help you solve your problems.

jQuery.download = function(url, data, method){
  //url and data options required
  if( url && data ){
    //data can be string of parameters or array/object
    data = typeof data == 'string' ? data : jQuery.param(data);
    //split params into form inputs
    var inputs = new Array();
    jQuery.each(data.split('&'), function(){
      var pair = this.split('=');
      inputs[inputs.length] = $('<input name="'+ decodeURIComponent(pair[0]) +'" type="hidden" />')
        .val(decodeURIComponent( pair[1].replace(/\+/g, " ")));
    });
    //send request
    jQuery('<form action="'+ url +'" method="'+ (method||'post') +'">'+'</form>').append(inputs)
    .appendTo('body').submit().remove();
  };
};

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>