Jquery convert response into file download

jquery convert response into file download

Reading binary data using jQuery Ajax. jQuery is an excellent tool to make web development easy and straightforward. It helps while doing DOM manipulation and makes Ajax requests painless across different browsers and platforms. But if you want make an Ajax request, which is giving binary data as a response, you will discover that it does not work for jQuery, at least for now. Changing "dataType" parameter to "text", does not help, neither changing it to any other jQuery supported Ajax data type. Problem here is that jQuery still does not support HTML5 XMLHttpRequest Level 2 binary data type requests ? there is even a bug in jQuery bug tracker, which asks for this feature. Although there is a long discussion about this subject on the GitHub, it seems that this feature will not become part of jQuery soon. To find a solution for this problem, we have to modify XMLHttpRequest itself. To read binary data correctly, we have to treat response type as blob data type. Parsing And Displaying CSV Files In jQuery - csv.js. csv.js is a jQuery based CSV parser that parses your CSV files and converts the CSV strings into JavaScript arrays and objects for further use. Ideal for dynamically generating data tables and data charts/graphs from CSV files. Supports both browser and node.js. Installation: How to use it: 1. Insert the main JavaScript file csv.js after jQuery JavaScript library. 2. Parse a single line of CSV data into an array of values. 3. Parse CSV data into a JavaScript 2D (two-dimensional) array. 4. Parse CSV data into an array of objects. 5. Convert arrays into a CSV string. 6. Convert objects into a CSV string. 7. Possible plugin options. 8. Event handlers. 9. Use the plugin in node.js. Changelog: change semistandard -> standard refactor fixtures rework npm scripts lint everything drop htmlhint. Updated. Bugfixed. fixed a bug where onParseValue was mistakenly being applied to the toObjects header fields fixed a bug where onPreParse wasn't updating the input csv string fixed errors to call throw Error instead of throw new Error fixed bug where that broke the Node.js callback convention when an empty options object was supplied. Cleanup. v0.8.12. This awesome jQuery plugin is developed by evanplaice. For more Advanced Usages, please check the demo page or visit the official website. jQuery Plugin To Export Table Data To CSV File - table2csv. Just another jQuery based table to CSV converter which exports your html table into a downloadable CSV file. Licensed under the GLP-3.0. See also: How to use it: 1. Load jQuery library and the jQuery table2csv plugin when needed.

2. Export your table into a downloadable CSV file.

3. Parse and output your table data in CSV format.

4. Specify the file name.

5. General settings with default values.

6. Return the csv as a string instead.

Changelog:

Add action to return the csv as a string.

Add BOM to the metadata of the downloaded file.

Fix bugs found after introducing tests.

Change MIME type to csv.

remove log messages.

This awesome jQuery plugin is developed by OmbraDiFenice. For more Advanced Usages, please check the demo page or visit the official website.

jQuery.parseHTML()

jQuery.parseHTML( data [, context ] [, keepScripts ] ) Returns: Array.

Description: Parses a string into an array of DOM nodes.

version added: 1.8 jQuery.parseHTML( data [, context ] [, keepScripts ] )

jQuery.parseHTML uses native methods to convert the string to a set of DOM nodes, which can then be inserted into the document. These methods do render all trailing or leading text (even if that's just whitespace). To prevent trailing/leading whitespace from being converted to text nodes you can pass the HTML string through jQuery.trim .

By default, the context is the current document if not specified or given as null or undefined . If the HTML was to be used in another document such as an iframe, that frame's document could be used.

As of 3.0 the default behavior is changed. If the context is not specified or given as null or undefined , a new document is used. This can potentially improve security because inline events will not execute when the HTML is parsed. Once the parsed HTML is injected into a document it does execute, but this gives tools a chance to traverse the created DOM and remove anything deemed unsafe. This improvement does not apply to internal uses of jQuery.parseHTML as they usually pass in the current document . Therefore, a statement like $( "#log" ).append( $( htmlString ) ) is still subject to the injection of malicious code.

Security Considerations.

Most jQuery APIs that accept HTML strings will run scripts that are included in the HTML. jQuery.parseHTML does not run scripts in the parsed HTML unless keepScripts is explicitly true . However, it is still possible in most environments to execute scripts indirectly, for example via the attribute. The caller should be aware of this and guard against it by cleaning or escaping any untrusted inputs from sources such as the URL or cookies. For future compatibility, callers should not depend on the ability to run any script content when keepScripts is unspecified or false .

Example:

Create an array of DOM nodes using an HTML string and insert it into a div.

Learning jQuery.

JSON (JavaScript Object Notation) is a way to store information in an organized manner. It is the preferred data-interchange format as its shorter, lightweight, human-readable and requires no tags like XML. This allows faster processing and transmission, and also the serializing and deserializing becomes much faster when compared to XML. JSON returned via REST APIs is used in different ways on the client side. You can populate data in HTML elements, display the JSON on the UI after formatting and convert it to CSV for exporting. This post provides jQuery solutions for formatting the JSON, converting it to CSV format, and showing the JSON data in an HTML table. Let?TMs begin!

Format JSON in jQuery.

Unformatted JSON is not human-readable and most of the time the JSON returned by REST APIs are not formatted, hence can?TMt be displayed directly on the UI. There are different ways to format it. Either using your own implementation or third-party plugins. Formatting the

JSON using jQuery can be done easily and requires only 2 function calls.

JSON.parse() - To parse a JSON string and convert it to a JavaScript object. JSON.stringify() - Convert a JavaScript object into a string. You can also apply indentation by passing an optional value.

The following jQuery code formats a JSON string:

Here, the formattedJson variable will have the formatted JSON string, indented using tab. To display formatted JSON on UI, use the tag only. If you want to display inside a div, you would need to first append the tag in the div element. Like:

You can check out the demo here.

Convert JSON to CSV.

If you want to convert JSON data to CSV for export purpose, the following jQuery code will help you. The following jQuery code defines a function called ConvertToCSV which takes JSON string, converts to CSV and returns it. Since it?TMs not compulsory to have comma as a delimiter for CSV, the delimiter is passed from outside which helps in changing the delimiter in the future without changing the actual function. The function first converts the JSON data into an array and then loops through the array to create a delimited string.

You can check out the demo here. The above function just creates a delimited string, it doesn?TMt allow you to save it as a .csv file. If you wish to export/download the JSON data into a CSV file with column headings and an optional report title, the following jQuery code provides a solution for the same. The modified function now expects 3 more parameters: report title, flag to display header, and a file name. While calling the function, please consider following things:

If you don?TMt wish to have a report title, pass an empty string. In case you don?TMt need a column header, pass ShowHeader as false. Pass the file name without the .csv extension.

The function does the following things:

First, parses the JSON data in an object, if not already. If report title is not empty, appends the title to the variable. If ShowHeader is true, then loop through the array?TMs 0th element to get the header columns and then appends them in the variable. Then loop the array to get the data and creates a delimiter separated string. Once the loop is completed, check the variable for any errors. An empty value means the JSON data is not correct. In such a case, it logs the error and exits the function. If everything is correct, then initialize file format. The file format is CSV in this case. Then it creates a temporary anchor tag and appends it to the HTML body with hidden visibility. Assigns the href and download attribute values and calls the anchor click function. Finally, removes it again from the body as it?TMs no longer needed.

Call this function on any event to convert the JSON data into a downloadable CSV file like:

You can check out the code in action here.

Convert JSON to HTML Table.

The following jQuery code will create a table element, populates the table data from JSON data and appends the table element to the HTML body. The function uses jQuery syntax for different table elements like header row and table row. Inside the JSON array loop, it appends the data in appropriate objects, and finally it is added to the HTML body.

Here the table formatting needs to be handled via CSS. You can also incorporate the same in this code with slight modifications. You can check out the code in action here.

Conclusion.

This post provides simple solutions for handling JSON on the client side in different ways. The jQuery implementation helps in formatting the unstructured JSON, converting the JSON data into a CSV string or downloadable CSV file with customization and displaying the JSON data in an HTML table. These jQuery codes are not dependent on any third-party plugins, which helps you to modify them as per your need without any hassle.

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download