3

I am posting some data to server through Backbone.js and server sends a csv file as response. As Backbone.js handles only json format can some body tell me how to handle this case, so that i would be able to download the csv file gracefully.

  object = {};
  object.c1 = formObj.c1
  hash = {
    success: function(model, response, options) {

    },
    error: function(model, response, options) {
      return console.log(response);
    }
  };
  model = new P.models.mine(object);
  model.doSomething(object, hash);

It always comes to error part.

Trying
  • 14,004
  • 9
  • 70
  • 110

2 Answers2

1

The ideal way to handle this would be to change your back end code to return JSON, or create another route that returns JSON. Since you are asking this question I'm assuming that isn't an option for you.

Basically you are going to have to parse the CSV on the client side:

https://stackoverflow.com/a/1293163/944006 - Should get you started.

If you are asking to download a csv file, then just pointing the browser at the location should prompt the user for download. You cannot prompt a file download through ajax(for good reason), but there are ways to tiptoe around this limitation:

https://stackoverflow.com/a/9970672/944006

Community
  • 1
  • 1
Thad Blankenship
  • 2,242
  • 3
  • 16
  • 16
  • My csv can be huge so the client side parsing is not an option. Thanks. – Trying Apr 16 '14 at 18:43
  • If you can't parse the csv in the client, then your only option is to change the server to deliver json – Stephen Thomas Apr 16 '14 at 18:45
  • Like @StephenThomas said, if you can't parse it, you need json to do anything dynamic with it. If you just want the csv file to be downloaded, then point the browser at the generated csv and it will prompt the user to download the file (assuming headers are set correctly). – Thad Blankenship Apr 16 '14 at 18:52
  • Please help me http://stackoverflow.com/questions/32589563/download-excel-in-backbone-js?noredirect=1#comment53042951_32589563 – vini Sep 18 '15 at 10:17
0

You could also use plain javascript rather than Backbone.js. Believe me this is the best way.

Here is some code:

var xhr = new XMLHttpRequest();
xhr.open('POST', Urls.download, true);
xhr.responseType = 'blob';
xhr.setRequestHeader("Authorization", "Bearer " + access_token);
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.onload = function (e) {
  if (this.status == 200) {
    var blob = new Blob([this.response], { type: 'application/vnd.ms-excel' });
    var downloadUrl = URL.createObjectURL(blob);
    var a = document.createElement("a");
    a.id = "a" + new Date().getTime();
    a.setAttribute("data-bypass", "");
    a.href = downloadUrl;
    a.download = "list_" + new Date().getTime() + ".xlsx";
    document.body.appendChild(a);
    a.click();
  } else {
    alert('Unable to download excel.')
  }
};
xhr.send(JSON.stringify(this.obj));
vini
  • 4,657
  • 24
  • 82
  • 170