views:

212

answers:

2

I have a form that posts to a url which triggers file download. The server is ASP.NET MVC and I write out a CSV file.

What I want to do is have a jQuery/javascript submit the form instead of a form submit button.

For example, I created a link and attached a handler using jQuery to submit the form:

$(function() {
    $("#mylink").click(function() {
        $("form").submit();
        return false;
    });
});

I also tried serializing the form and doing an ajax post with same result.

What I get is that the request/response happens as should, but I do not get the file download (save file) dialog. I can verify the response by using fiddler for example.

It's as if the response is happening out of band or something, in a parallel thread if you will, there is no one at the door.

Can someone shed a light? Thanks

UPDATE For some reason, $("form").submit() does not work but I can do my validation and pre-processing, then return true, which works.

A: 

If you call the submit method on a form, then that is exactly the same as clicking a normal submit button.

Using XHR would fail (since the file would be handled by XHR instead of the normal browser response handler), but .submit() should work.

It sounds like you just aren't setting the content-disposition header to cause the browser to treat the data as an attachment instead of an inline document.

David Dorward
I am setting content-disposition alright - like I said, I can see it in fiddler. I got you regarding XHR bit. I'm also not sure why submit() does not work. I will double-check the form request. Perhaps the field that it's looking for as an indicator for the server to start file download is not getting through.
Jiho Han
A: 

I want exactly this. What I need is: to submit a form and:

  1. If the form is invalid [I receive an Json encoded message with the errors], I have to display the errors
  2. If the response is a FILE [how do I know that], I want to output the response[file].

As solution I propose:

  1. check whether the form has errors [with the Ajax submit]
  2. If no errors, simply post the Form normally [no Ajax] and download the URL
Andrei Iarus