XMLHttpRequest() and outputting csv file

Posted by sjw on Stack Overflow See other posts from Stack Overflow or by sjw
Published on 2010-04-30T03:49:34Z Indexed on 2010/04/30 3:57 UTC
Read the original article Hit count: 245

Filed under:
|

Initially, I developed a javascript function to use window.open to post contents of a form to a new window which simply opened the new window and initiated a csv file download.

Now on reflection, I find the opening of the window superfluous and am trying to just execute a XMLHttpRequest() to download the csv.

I am not getting what I want and I'm not 100% sure that I can so I thought I'd ask here for some assistance.

When a form is submitted, I want to take all the form values and post them to another page which builds an SQL string and builds a csv based on the contents. (This I can do and works fine with XMLHttpRequest() as seen below)

var xhReq = new XMLHttpRequest();
var parameters = "";

for ( i=0; i<formObj.elements.length; i++ ) {
  parameters += formObj.elements[i].name + "=" + encodeURI( formObj.elements[i].value ) + "&";
}

xhReq.open("POST", outputLocation, false);
xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhReq.setRequestHeader("Content-length", parameters.length);
xhReq.setRequestHeader("Connection", "close");
xhReq.send(parameters);

document.write(xhReq.responseText);

The code above calls the page ok, builds the csv ok, but it outputs the contents into the current browser window instead of initiating a csv file download.

Can I achieve what I need using XMLHttpRequest() or am I going it about it the wrong way?

Thanks

© Stack Overflow or respective owner

Related posts about xmlhttprequest

Related posts about JavaScript