How I used jQuery to push a dynamically generated file to the web browser based on the user’s input

There are times when we want to push a dynamically generated file to our users based on their inputs. That file could be an excel file that holds payment transaction reports for a time period or a tabulation of guest names who had accepted invitations to our corporate house warming.

In such cases, the user should be presented with a dialog box which lets him decide whether to save it somewhere in her local filesystem or open the file for viewing with an appropriate application in his computer.

For example, in my tool for generating boilerplate coding from a list of country names, I am presented with some input fields where I can submit some instructions to format the output of the boilerplate coding. And upon clicking on the "Generate" button, I am shown a dialog box that looks like the following:

Image of firefox dialog box after submitting request to generate some files.

Let's cook up a simple scenario to demonstrate this idea with jQuery.

Suppose we are creating a simple game for the user to draw a random number. For this, we have a text field for the user to write his name. There will be a number dial that changes at random. When the user clicks on the "Get lucky number" button, the browser will present a text file for the user to download.

The text file will contain the user's name and the number taken from the number dial at the instance when he clicks on the button.

The client side stuff

As a start, I construct the visuals for the scenario by referencing my HTML code reference.

The HTML portion

<strong>Your lucky number</strong>: <span id="luckyNumberDial"></span>

<form>
	<label for="nameTextField">Your name</label>
	<input id="nameTextField" type="text"/>
	<input id="genFileButton" type="button" name="genFileButton" value="Get lucky number"/>
</form>

<form id="DataCarrierForm" method="post" 
    action="/process/proof-of-concepts/userNameAndLuckyNumberTextFileGeneration">
	<input name="visitorName" id="visitorName" type="hidden"/>
	<input name="luckyNumber" id="luckyNumber" type="hidden"/>
</form>

In the body section of the HTML document, I designated a span section (with id luckyNumberDial) to contain a random number that changes periodically. I then created a HTML form that contains a text field (with id nameTextField) for my user to enter his name and a button (with id genFileButton) labelled with the text "Get lucky number" for the user to click.

There is another form (with id DataCarrierForm) that contains two hidden input to hold the user's name and the lucky number that he had drawn. This form will be used for sending the user's name and the lucky number to the server endpoint, via HTTP post.

The JavaScript portion

Next in line was to code the JavaScript portion.


function setRandomNumber() {
	$('#luckyNumberDial').html(Math.floor((Math.random()*9999)+1));
	setTimeout(setRandomNumber, 50);
}

function downloadFile() {
	$('#visitorName').val($('#nameTextField').val());
	$('#luckyNumber').val($('#luckyNumberDial').html());
	$('#DataCarrierForm').submit();
}

$('#genFileButton').click(
	function() {
		downloadFile();
	}
);

setRandomNumber();

The JavaScript portion contains two function declarations and two function calls:

  • The setRandomNumber function computes a random number from 1 to 9999 and calls the setTimeout function to call itself again recursively.
  • The downloadFile function extracts the user's name and the random number at the number dial to populate the hidden fields with ids visitorName and luckyNumber respectively.

    It then tells the browser to submit the form with id DataCarrierForm. The browser then posts the data contained in the hidden fields with id visitorName and luckyNumber to the server endpoint via HTTP post.

  • The call to $('#genFileButton').click then registers an anonymous function to call the downloadFile function when the user clicks the button with id genFileButton.
  • The call to setRandomNumber then starts the number dial running.

The server backend stuff

After coding the client side aspect of my solution, I proceeded to code the server endpoint located at /process/proof-of-concepts/userNameAndLuckyNumberTextFileGeneration.

<?php
if (isset($_POST['visitorName']) && isset($_POST['luckyNumber'])) {
	// Specify that the output is going to be a text document.
	header('Content-type: plain/text');
	// Tell browsers to open up the download dialog box to download
	// our yourLuckyNumber.txt. In addition, the browser should default the 
	// file name to yourLuckyNumber.txt
	header('Content-Disposition: attachment; filename="yourLuckyNumber.txt"');
 
		// Write the contents to the browser
	echo 'Hi ' . $_POST['visitorName'] . '. ' . PHP_EOL;
	echo 'You have drawn the number ' . $_POST['luckyNumber'] . '.' . PHP_EOL;
}
else {
	header('HTTP/1.0 400 Bad Request');
}

At the start of the server script, I checked whether there are HTTP post data being sent to the script by looking into $_POST['visitorName'] and $_POST['luckyNumber']. If the user's name and the lucky number are available, I used the same techniques discussed in PHP codes to tell browsers to open the download dialog box for users to download a file to send the HTTP response as a text file back to the browser. In that HTTP response, I writes the user's name and the lucky name that she had drawn.

If there is nothing for my server script to process, I returns a HTTP 400 as the response.

With that, I demonstrated the concept of pushing a dynamic generated file for the user to download in a web browser based on his/her input.

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.