Jonathan Bechtel
Jonathan Bechtel

Reputation: 3607

Jquery Initiated Download Returning 'Failed: Network Error'

I'm using a JQuery AJAX request that will trigger a download upon its completion.

CODE:

 $('.getPDF').click(function(){
 var filepath = 'localhost:3000/pdf/formula-' + this.id + '.pdf';
 $.ajax({
   url: '/formulas/'+ this.id +'/pdf',
   type: 'POST',
   success: downloadFile(filepath)
 });

 function downloadFile (path) {
   var link = document.createElement('a');
   link.href = path;
   $(link).attr("download", true);
   link.click();
   }
 });

This returns the following error in Chrome:

Failed - Network Error

with nothing else showing up in the console. The download does not work in Firefox or IE either.

I've done a console.log(filepath) in success, and the route it returns shows the correct file when I paste it into the browser-bar as a URL.

The HTML generating the AJAX Request looks like this:

<a class="pure-button button-success getPDF" id="59ac514a52c93e4aa862fadd">Generate PDF </a>

If it's relevant, the server side code generically looks like this:

router.post('/formulas/:id/pdf', function(req, res){
  var db = req.db.collection('users');
  var id = new ObjectID(req.params.id);
  var pointer = {"formulas.$": 1, "_id": 0};
  db.aggregate([
    {$match: {"formulas.f_id": id}},
    {$unwind: "$formulas"},
    {$match: {"formulas.f_id": id}},
    {$project : {"formulas": 1, "_id": 0}}
  ]).toArray(function(e, doc){
    if (e) {
    throw e;
  } else {
    var html = null;
   ejs.renderFile('./views/pdf.ejs', {
    project: doc[0].formulas
  }, function(err, results){
    if (err) {
      console.log(err);
      }
      html = results;
    });
    var options = { format: 'Letter' };
    var path = 'public/pdf/formula-' + req.params.id + '.pdf';
    pdf.create(html, options).toFile(path, function(err, results) {
      if (err) {
        return console.log(err);
      }
      if (results) {
        res.end();
      }
    });
   }
  });
});

Upvotes: 0

Views: 613

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

The Ajax success callback has to be a function...
The first argument can be named as you wish... But will be filled with the Ajax response.

So the response is overwriting your filepath variable...
To avoid this, call downloadFile within a callback function.
And just ignore the response if you don't need it. ;)

success: function(response){
  downloadFile(filepath);
}

Upvotes: 1

Related Questions