5

I have a link on the website to a php file that generates native excel file on a fly ant outputs it directly to browser via headers for user to to open/save. Since it takes some time for the file to be generated I'd like to use jQuery Ajax to make the call and use some loading animation in the mean while.

The only thing I'm not sure how to do is how to output the file into the browser after Ajax call? Is it even possible?

1
  • How about deactivating the link when user clicks on it and providing a message that says something like "Please wait while the file is being generated..". This way you WILL provide a feedback to your user. Commented Sep 15, 2011 at 11:57

3 Answers 3

3

(N.B. This is a paraphrasing of @dmitry's answer, but just elaborated upon)

The problem you have is that there is no means of directly returning a file to the user via AJAX - the browser has to request the file using a normal, synchronous HTTP request.

To solve this, your PHP will need to:

  1. Generate the Excel file as normal.
  2. Instead of writing the file back to the user, save it somewhere on the server's filesystem (i.e. using file_put_contents() or similar).
  3. Return the file path to the user.

Your JS, on receiving this response will then need to:

  1. Read the Excel file path back from the PHP script.
  2. Open the Excel file in a new tab/window using window.open() (or redirect in the current tab/window by setting location.href).
Sign up to request clarification or add additional context in comments.

Comments

1

I think you can make a trick: generate file and return path to generated file in your Ajax response and then just call

window.location = fileUrl

also there some techniques with iframe Ajax

Comments

0

Why don't you use iframe where you load the actual php file that generates the excel file? That way you won't block the UI while the file is being generated and browser will trigger download dialog.

There's no way that you can send a file via javascript, at least not in the manner of forcing the browser to open the download dialog.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.