Kendo UI Grid Export CSV using Javascript - javascript

please help me my probs,am using kendo ui grid in my webapp & trying to grid data export into EXcel and CSV format. Code Works good in Chrome and files are downloading, but in Fire Fox its open a new window show the grid details in url and says bad request,
//code is
$("#exportcsv").click(function (e) {
debugger
var dataSource = $("#grid").data("kendoGrid").dataSource;
var filteredDataSource = new kendo.data.DataSource({
data: dataSource.data(),
filter: dataSource.filter()
});
filteredDataSource.read();
var data = filteredDataSource.view();
//start with the desired column headers here
var result = "\"ID\",\"EID\",\"Name\",\"Company Name\",\"Salary\",\"DID\",\"Date Of Join\"";
//each column will need to be called using the field name in the data source
for (var i = 0; i < data.length; i++) {
result += "\n";
result += "\"" + data[i].id + "\",";
result += "\"" + data[i].EID + "\",";
result += "\"" + data[i].EName + "\",";
result += "\"" + data[i].CName + "\",";
result += "\"" + data[i].Salary + "\",";
result += "\"" + data[i].DID + "\",";
result += "\"" + data[i].DOJ + "\",";
}
if (window.navigator.msSaveBlob) {
//Internet Explorer
window.navigator.msSaveBlob(new Blob([result]), 'ExportedKendoGrid.csv');
}
else if (window.webkitURL != null) {
//Google Chrome and Mozilla Firefox
var a = document.createElement('a');
result = encodeURIComponent(result);
a.href = 'data:application/csv;charset=UTF-8,' + result;
a.download = 'ExportedKendoGrid.csv';
a.click();
}
else {
//Everything Else
window.open(result);
}
e.preventDefault();
});
//below code is not working in firefox browser else if
(window.webkitURL != null) {
//Google Chrome and Mozilla Firefox
var a = document.createElement('a');
result = encodeURIComponent(result);
a.href = 'data:application/csv;charset=UTF-8,' + result;
a.download = 'ExportedKendoGrid.csv';
a.click();
}

Related

Sheet JS using spaces in excel file headers

I'm using SheetJS to parse out an externally linked excel spreadsheet and create some HTML elements.
Overall, the way that I have it set up is fine, but I noticed that if the excel sheet that I'm referencing has spaces in the header (e.g. - First Name, Last Name, etc.) it won't recognize that and errors out. And I'm not sure how to go about accommodating the spaces in the headers.
Here's what I have:
Excel File Data:
JS:
var url = "https://assets.codepen.io/8689/test2.xlsx";
/* set up XMLHttpRequest */
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
/* Call XLSX */
var workbook = XLSX.read(bstr, { type: "binary" });
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
var jData = XLSX.utils.sheet_to_json(worksheet, { raw: false });
$.each(jData, function (i, f) {
var el =
"<div class='thing'>" +
"<h2>" +
f.First Name +
" " +
f.Last Name +
"</h2>" +
"<h3>" +
f.Title +
"</h3>" +
"<p>" +
f.Comment +
"</p>" +
"</div>";
$(el).appendTo("#wrapper");
});
console.log(jData);
};
oReq.send();
I know that f.First Name and f.Last Name will error out, and I'm not sure what I can do to try and get it to accommodate the space. I tried an underscore, but that obviously doesn't work either (I kind of figured, but I wanted to test to be sure).
Ok, I did some more digging and I realized that since this is JSON data that is being parsed, I can use bracket notation to help parse that out:
$.each(jData, function (i, f) {
var el =
"<div class='thing'>" +
"<h2>" +
f["First Name"] +
" " +
f["Last Name"] +
"</h2>" +
"<h3>" +
f.Title +
"</h3>" +
"<p>" +
f.Comment +
"</p>" +
"</div>";
});

My code/javascript sometimes works in Internet Explorer and sometimes doesn't. It works in all other browsers

I've created a directory search feature and uses an ajax call to a file within the project folder. It works in Chrome and Firefox, but only sometimes works in Internet Explorer.
I have gotten it to work in Internet Explorer, but this requires me to copy and paste the code into a new folder and hope that it works. This is strange behavior because I'm not changing a single thing in the code and it will sometimes work.
If I get it to work on Internet Explorer and copy/paste the "working" files - it doesn't always work again.
Originally I was using some ES6 that isn't supported by IE, but I have fixed those issues. I think it might be something wrong with the .ajax call? But I can't figure out what.
AJAX Call
function getADInfo(){
$.ajax({
url: "../../js/roster.json",
method: 'GET',
dataType: 'json',
cache: false,
success: function(data) {
console.log('success from getADInfo');
// employees.push(...data);
Array.prototype.push.apply(employees, data);
},
error: function(err) {
console.error(err);
}
});
}
This should search through the json file and display matches
function findMatches(wordToMatch, employees) {
return employees.filter(function(person) {
var regex = new RegExp(wordToMatch, 'gi');
var nameString = person.Name.split(", ")[1] + " " + person.Name.split(", ")[0];
var displayFirstName = person.DisplayName.split(", ")[1];
return person.GivenName.match(regex) || person.Surname.match(regex) || nameString.match(regex) || displayFirstName.match(regex);
});
}
function displayMatches() {
$('.suggestions').show();
var matchArray = findMatches(this.value, employees);
// var html = matchArray.slice(0,10).map(person => {
// var regex = new RegExp(this.value, 'gi');
// var firstName = person.GivenName.replace(regex, `<span class="hl">${this.value}</span>`);
// var lastName = person.Surname.replace(regex, `<span class="hl">${this.value}</span>`);
// var extension;
// if (person.Phone_Ext1 !== null){
// extension = person.Phone_Ext1;
// } else {extension = "N/A"}
// return `
// <li class="search-item" data-id=${person.EmployeeID}>
// <span class="person">${firstName} ${lastName}</span>
// <span class="phone-ext">Ext. ${extension}</span>
// </li>
// `
// }).join('');
var html = [];
for(var i=0; i < matchArray.slice(0,10).length; i++){
var person = matchArray.slice(0,10)[i];
var regex = new RegExp(this.value, 'gi');
var hilight = '<span class="hl">' + this.value + '</span>';
var firstName = person.GivenName.replace(regex, hilight);
var lastName = person.Surname.replace(regex, hilight);
var extension;
var showdisplayname;
if (person.DisplayName.split(", ")[1] !== person.GivenName){
showdisplayname = "(" + person.DisplayName.split(", ")[1] + ")";
showdisplayname = showdisplayname.replace(regex, hilight);
} else {
showdisplayname = "";
}
if (person.Phone_Ext1 !== null){
extension = person.Phone_Ext1;
} else {
extension = "N/A"
}
var list =
'<li class="search-item" data-id=' + person.EmployeeID +'>' +
'<span class="person">' + firstName + ' ' + lastName + ' ' + showdisplayname + '</span>' +
'<span class="phone-ext">Ext. ' + extension + '</span>' +
'</li>';
html.push(list);
}
html = html.join('');
if ($('#search-box').val() == ""){
suggestions.innerHTML = "";
} else {
suggestions.innerHTML = html;
}
}
A dropdown should appear as I type, but nothing happens on Internet Explorer. It works fine on other browsers.
When I check the console, I'm getting a status 200, but it's an error
Example

Modifying innerHTML in nested get() jQuery

I'm currently using the jQuery get method to read a table in another page which has a list with files to download and links to others similar webpages.
$.get(filename_page2, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find(target_element_type_page2 + '#' + target_element_id_page2)[0];
var container = document.getElementById(element_change_content_page1);
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var isFolder = table.getAttribute("CType") == "Folder";
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link = elem.getElementsByTagName("A")[0].getAttribute("href");
if (!isFolder) {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + link + "\">" + text + "</a></li>";
} else {
container.innerHTML += "<li class=\"folderlist\">" + "<a class=\"folderlink\" onclick=\"open_submenu(this)\" href=\"#\">" + text + "</a><ul></ul></li>";
var elem_page1 = container.getElementsByTagName("li");
var container_page1 = elem_page1[elem_page1.length - 1].getElementsByTagName("ul")[0];
create_subfolder(container_page1, link);
}
}
} else {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + "#" + "\">" + "Error..." + "</a></li>";
}
}, page2_datatype);
This is working fine, and all the folders and files are being listed. But when I try to do the same thing with the folders (calling the create_subfolder function) and create sublists with their subfolders and files, I'm getting a weird behavior.
function create_subfolder(container2, link1) {
$.get(link1, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find("table" + "#" + "onetidDoclibViewTbl0")[0];
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link2 = elem.getElementsByTagName("A")[0].getAttribute("href");
//nothing is changed in the webpage. The modifications in the html don't appear
container2.innerHTML += "<li>" + text + "</li>";
}
}
alert(container2.innerHTML); // Print the html with all the modifications
}, "html");
}
The second get(), inside the create_subfolder() function are not changing anything in the webpage, so no sublist is created. But, when I call the alert() function at the end of the get() function, it prints the code with all the modifications it should have made in the html at the second get callback. I believe the problem is related with the asynchronous behavior of the get function but I don't know exactly why. Any guess?

Memory issue exporting many JSON records to CSV

I am using the code below to export nearly 3,000 JSON records to CSV format. It is working in Chrome and Opera but not in Safari, IE, or Firefox. I have an "out of browser memory" issue.
Why doesn't it work in those browsers?
How can I export many (e.g. 90,000) records in any browser?
function exportAll(JSONData, ReportTitle, ShowLabel) {
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
CSV += ReportTitle + '\r\n\n';
if (ShowLabel) {
var row = "";
for (var index in arrData[0]) {
row += index + ',';
}
row = row.slice(0, -1);
CSV += row + '\r\n';
}
for (var i = 0; i < arrData.length; i++) {
var row = "";
for (var index in arrData[i]) {
row += '"' + arrData[i][index] + '",';
}
row.slice(0, row.length - 1);
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
var link = document.createElement("a");
link.id = "lnkDwnldLnk";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
var csv = CSV;
blob = new Blob([csv], {
type: 'text/csv'
});
var csvUrl = window.webkitURL.createObjectURL(blob);
var filename = 'GraphsData.csv';
$("#lnkDwnldLnk")
.attr({
'download': filename,
'href': csvUrl
});
$('#lnkDwnldLnk')[0].click();
document.body.removeChild(link);
}

Converting firefox javascript to IE javascript

I've been trying to get some AJAX code that runs fine in FireFox to run in IE.
I'm running into some trouble with updating some tables in the script though. I've seen numerous other people have similar issues, but none of the solutions they've found have worked for me. The problem occurs first on the line
qe3Table.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
Where I'm getting the error "'null' is null or not an object"
I'm pretty sure that all of my other errors are of the same type as this one, my AJAX script and some accompanying javascript is below.
<script type="text/javascript">
<!--
//obtains the box address for a QE3 on the system for the given index
function getQE3BoxAddressHash(index)
{
var retVal = 0x00000100; //initial value for QE3 boxes
retVal |= (index & 0x000000FF);
return retVal;
}
//obtains the box address for a QED on the system for the given index
function getQEDBoxAddressHash(index)
{
var retVal = 0x00001300; //initial value for QED boxes
retVal |= ((index & 0x0000000F) << 4);
retVal |= ((index & 0x000000F0) >> 4);
return retVal;
}
-->
</script>
<script type="text/javascript">
<!--
var textSocket;
function fillTables()
{
if(textSocket.readyState != 4)
return;
var qe3Table = document.getElementById("QE3_TABLE");
var qedTable = document.getElementById("QED_TABLE");
var rawData = textSocket.responseText.split("::::");
var qe3Data = new Array();
var qedData = new Array();
var qe3Index = 0;
var qedIndex = 0;
for(var item in rawData)
{
if(rawData[item].indexOf("QA") != -1)
{
qe3Data[qe3Index++] = rawData[item];
}
else if(rawData[item].indexOf("QED") != -1)
{
qedData[qedIndex++] = rawData[item];
}
}
qe3Table.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
qedTable.innerHTML =
"<tr>\n" +
" <th>Name</th>\n" +
" <th>Status</th>\n" +
" <th>View Status</th>\n" +
"</tr>\n";
for(var value in qe3Data)
{
var components = qe3Data[value].split("-");
if(components.length != 3)
continue;
qe3Table.innerHTML +=
"<tr>\n" +
" <td>" + components[0] + "-" + components[1] +"</td>\n" +
" <td>" +
((components[2].toUpperCase() === "ONLINE")?
"<font color=\"green\"><b>ONLINE</b></font>":
"<font color=\"red\"><b>OFFLINE</b></font>")+
"</td>\n" +
" <td>\n <input type=\"button\" onclick=\"window.location='system_status.php?boxAddress=" + getQE3BoxAddressHash(value).toString(16) + "'\" value='View Status for " + components[0] + "-" + components[1] +"'></input> </td>\n" +
"</tr>\n";
}
for(var value in qedData)
{
var components = qedData[value].split("-");
if(components.length != 3)
continue;
qedTable.innerHTML +=
"<tr>\n" +
" <td>" + components[0] + "-" + components[1] +"</td>\n" +
" <td>" +
((components[2].toUpperCase() === "ONLINE")?
"<font color=\"green\"><b>ONLINE</b></font>":
"<font color=\"red\"><b>OFFLINE</b></font>")+
"</td>\n" +
" <td>\n <input type=\"button\" onclick=\"window.location='system_status.php?boxAddress=" + getQEDBoxAddressHash(value).toString(16) + "'\" value='View Status for " + components[0] + "-" + components[1] +"'></input> </td>\n" +
"</tr>\n";
}
}
function initAjax()
{
try
{
// Opera 8.0+, Firefox, Safari
textSocket = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try
{
textSocket = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
textSocket = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("A browser error occurred.");
return false;
}
}
}
textSocket.onreadystatechange=fillTables
}
function reloadTables()
{
textSocket.open("GET","ajax_scripts/get_connected_boxes.php",true);
textSocket.send(null);
}
function init()
{
initAjax();
reloadTables();
}
window.onload=init();
-->
</script>
The problem is probably with:
var qe3Table = document.getElementById("QE3_TABLE");
If you're running this script before the body is loaded, that won't exist. Check to see if that variable has anything in it.
I Tried both of your guys' fixes but they didn't seem to help. In the end, I converted all calls of the form:
qe3TableNew.innerHTML = ("<tr>\n" +" <th>Name</th>\n" +" <th>Status</th>\n" +" <th>View Status</th>\n" +"</tr>\n");
to
var row;
var cell;
var text;
var font;
row = document.createElement("tr");
qe3TableNew.appendChild(row);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("Name");
cell.appendChild(text);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("Status");
cell.appendChild(text);
cell = document.createElement("th");
row.appendChild(cell);
text = document.createTextNode("View Status");
cell.appendChild(text);
This seemed to solve it, so I believe it has to do with IE's inability to handle changes to innerHTML.
Thanks for the help guys.
At least one issue (which could produce the above symptoms) is the line:
window.onload=init();
Hint: the () operator executes the function immediately and evaluates to the return value. This in turn may allow the XHR handler (in certain situations) to fire at a time when the DOM may not be ready.
Happy coding.

Categories

Resources