How to data Export to CSV using JQuery or Javascript - javascript

What I needed:
We have value in the response.d that is comma deliminated value. Now I want to export the data of response.d to .csv file.
I have written this function to perform this. I have received the data in response.d but not exporting to the .csv file, so give the solution for this problem to export data in .csv file.
function BindSubDivCSV(){
$.ajax({
type: "POST",
url: "../../WebCodeService.asmx / ShowTrackSectorDepartureList",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);//export to csv function needed here
},
error: function (data) {}
});
return false;
}

In case you have no control over how the server-side works, here is a client-side solution that I have offered in another SO question, pending for that OP's acceptance: Export to CSV using jQuery and html
There are certain restrictions or limitations you will have to consider, as I have mentioned in my answer over there, which has more details.
This is the same demo I have offered:
http://jsfiddle.net/terryyounghk/KPEGU/
And to give you a rough idea of what the script looks like.
What you need to change is how you iterate your data (in the other question's case it was table cells) to construct a valid CSV string. This should be trivial.
$(document).ready(function () {
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td)'),
// Temporary delimiter characters unlikely to be typed by keyboard
// This is to avoid accidentally splitting the actual contents
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
// actual delimiter characters for CSV format
colDelim = '","',
rowDelim = '"\r\n"',
// Grab text from table into CSV formatted string
csv = '"' + $rows.map(function (i, row) {
var $row = $(row),
$cols = $row.find('td');
return $cols.map(function (j, col) {
var $col = $(col),
text = $col.text();
return text.replace('"', '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim) + '"',
// Data URI
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
$(this)
.attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
}
// This must be a hyperlink
$(".export").on('click', function (event) {
// CSV
exportTableToCSV.apply(this, [$('#dvData>table'), 'export.csv']);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
});

Using the code above (from Terry Young) I found that in Opera it would refuse to give the file a name (simply calling it "download") and would not always work reliably.
To get it to work I had to create a binary blob:
var filename = 'file.csv';
var outputCSV = 'entry1,entry2,entry3';
var blobby = new Blob([outputCSV], {type: 'text/plain'});
$(exportLink).attr({
'download' : filename,
'href': window.URL.createObjectURL(blobby),
'target': '_blank'
});
exportLink.click();
Also note that creating the "exportLink" variable on the fly would not work with Firefox so I had to have this in my HTML file:
<div>
<a id="exportLink"></a>
</div>
Using the above I have successfully tested this using Windows 7 64bit and Opera (v22), Firefox (v29.0.1), and Chrome (v35.0.1916.153 m).
To enable similar functionality (albeit in a far less elegant manner) on Internet Explorer I had to use Downloadify.

Related

I'm missing something to send long audios recorded in the web browser to oracle apex?

I am trying to send recorded audio from the web browser to Oracle Apex but a problem is happening when the audio is quite long. The code works very well when the audio is less than two minutes.
What I know, the data is sent by URL, therefore it is being sent in text format. Oracle has a 32k limit for the string, so if the blob exceeds that limit, it must be sent in an array divided into parts of 30k each. So I am suspecting that the array is not being sent in the correct format, but I don't know how to confirm it.
The code I am using is as follows: (I built a plugin for Apex to send the audio)
Fragment in Javascript that sends the audio:
// builds a js array from long string
clob2Array: function(clob, size, array) {
loopCount = Math.floor(clob.length / size) + 1;
for (var i = 0; i < loopCount; i++) {
array.push(clob.slice(size * i, size * (i + 1)));
}
return array;
},
// converts DataURI to base64 string
dataURI2base64: function(dataURI) {
var base64 = dataURI.substr(dataURI.indexOf(',') + 1);
return base64;
},
blobToDataURL: function(blob, callback) {
var a = new FileReader();
a.onload = function(e) {callback(e.target.result);}
a.readAsDataURL(blob);
},
// save to DB function
save2Db: function(pAjaxIdentifier, pRegionId, pAudio, callback) {
apexAudio.blobToDataURL(pAudio, function(data){
// audio DataURI to base64
var base64 = apexAudio.dataURI2base64(data);
// split base64 clob string to f01 array length 30k
var f01Array = new Array();
f01Array = apexAudio.clob2Array(base64, 30000, f01Array);
// Apex Ajax Call
apex.server.plugin(pAjaxIdentifier, {
f01: f01Array,
}, {
dataType: 'html',
// SUCESS function
success: function() {
// add apex event
$('#' + pRegionId).trigger('apexaudio-saved-db');
// callback
callback();
},
// ERROR function
error: function(xhr, pMessage) {
// add apex event
$('#' + pRegionId).trigger('apexaudio-error-db');
console.log('save2Db: apex.server.plugin ERROR:', pMessage);
// callback
callback();
}
});
});
}
The PL/SQL Code that receives adn transforms the string array into blob
DECLARE
--
l_collection_name VARCHAR2(100);
l_blob BLOB;
l_filename VARCHAR2(100);
l_mime_type VARCHAR2(100);
l_token VARCHAR2(32000);
--
BEGIN
-- get defaults
l_filename := 'audio_' || to_char(SYSDATE, 'YYYYMMDDHH24MISS') || '.webm';
l_mime_type := 'audio/webm';
-- build BLOB from f01 30k Array
dbms_lob.createtemporary(l_blob,
TRUE,
dbms_lob.session);
FOR i IN 1 .. apex_application.g_f01.count LOOP
l_token := wwv_flow.g_f01(i);
IF length(l_token) > 0 THEN
dbms_lob.append(l_blob
,to_blob(utl_encode.base64_decode(utl_raw.cast_to_raw(l_token))));
END IF;
END LOOP;
l_collection_name := 'APEX_AUDIO';
APEX_COLLECTION.CREATE_OR_TRUNCATE_COLLECTION(
p_collection_name => l_collection_name);
-- add collection member (only if BLOB not null)
IF dbms_lob.getlength(l_blob) IS NOT NULL THEN
apex_collection.add_member(p_collection_name => l_collection_name,
p_c001 => l_filename, -- filename
p_c002 => l_mime_type, -- mime_type
p_d001 => SYSDATE, -- date created
p_blob001 => l_blob); -- BLOB audio content
END IF;
END;
I repeat, the code works perfectly if the audio is short, but if it is long, the following error arises:
2020-02-20T20:09:27.169Z SEVERE <P-fvMwI2WpKybDySZRumRQ> java.sql.SQLException: ORA-06550: line 2, column 2:
PLS-00306: number or wrong type arguments when calling 'AJAX'
ORA-06550: line 2, column 2:
PL/SQL: Statement ignored
InternalServerException [statusCode=500, reasons=[]]
at oracle.dbtools.apex.ModApexContext.handleError(ModApexContext.java:288)
at oracle.dbtools.apex.OWA.execute(OWA.java:206)
at oracle.dbtools.apex.ModApex.handleRequest(ModApex.java:310)
at oracle.dbtools.apex.ModApex.doPost(ModApex.java:188)
at oracle.dbtools.apex.ModApex.service(ModApex.java:112)
at oracle.dbtools.http.entrypoint.Dispatcher.dispatch(Dispatcher.java:126)
[...]
Tecnology:
Oracle 12c
Oracle Apex 19.2
Ords 19.4
Tomcat 8
Thus you are sending your request using AJAX with content type "application/x-www-form-urlencoded" Tomcat is limiting the max allowed POST size (defaults to 2MB).
To make it work in APEX you have possibly 2 ways
1) Do some kind of double chunked upload, so first you split the file itself with e.g. file.slice() and then you build the 30k base64 array of each file chunk and upload this, chunk by chunk
2) Use a "multipart/form-data" content type with an form submit, thus here you are not running in Tomcats limitation of 2MB.
I built a file uploader plugin some time ago, just have a look at this function:
https://github.com/Dani3lSun/apex-plugin-dropzone/blob/90a82f4bb83fee9d78458af790560fb6c5b77978/server/js/apexdropzone.js#L378
The uploaded file will then be inserted into apex_application_files automatically, from there you can grab it:
https://github.com/Dani3lSun/apex-plugin-dropzone/blob/90a82f4bb83fee9d78458af790560fb6c5b77978/source/render_region.sql#L332
I would not recommend doing it with ORDS when you can do it inside of your APEX app, thus you have to deal with security, additional authentication etc...

How can I divide a string into parts in jquery

I have this code below I just need to divide the string into parts in the onSelect parameter of auto complete function
$(function(){
$('#business_category').autoComplete({
minChars: 2,
source: function(term, response){
term = term.toLowerCase();
var countryName = $("select[name=country]").val();
var data_search_term = $("input[name=business_category]").val();
console.log(countryName);
$.ajax({
type: "POST",
url: "ajax/businesses_search_terms_count.php",
data: "countryName=" + countryName + "&searchTerm=" + data_search_term,
dataType: "json",
success: function(resp){
response(resp.data)
}
});
},
onSelect: function(event, term, item) {
console.log("searchedItem: " + term);
var data_search_term = $("input[name=business_category]").val();
$('#total-count').html(data_search_term);
}
});
});
Right now, when user selects any category my output is: (Audio and video => 6,488). But I want an output like this: (Audio and video). So I just want a string with the category field not with count number like => 6,488
As #Donny stated, you can achieve it with pure Javascript. My solution is very similar to his but I just wanted to share a little bit more concise solution using template strings:
const str = "(Audio and video => 6,488)";
console.log(`${str.split("=>")[0].trim()})`);
You can achieve your goal using pure JavaScript with string.split() and string.trim()
var str = "(Audio and video => 6,488)";
var res = str.split("=>")[0]; //Turn string into array splitting by '=>' and get the first element
res = res.trim(); //Remove side spaces
res += ')'; //add ')' to the end of the string
console.log(res); //prints to console '(Audio and video)'

Convert base64 strings to byte array

On the page you need to load in the input type file, as well as display this image in img. And then ajax request to transfer the base64 string to the server and there translate it into an array of bytes. Here is my view code:
$('#modalWindow').on('click', '#send', function () {
var file = $('#autoPicture').attr('src');
var formData = new FormData();
formData.append("base64img", file);
$.ajax({
type: "POST",
url: "/Home/LoadImage",
data: $('form').serialize() + "&base64img=" + formData.get('base64img'),
success: function (data) {
alert('Success');
},
error: function (error) {
alert(error.responseText);
}
});
});
Controller code:
public ActionResult LoadImage(Car car, string base64img)
{
var base64arr = base64img.Split(',');
byte[] picture = Convert.FromBase64String(base64arr[1]);
return View();
}
But when you try to convert crashes with the text:
The input is not a valid Base-64 string because it contains a character in an encoding other than Base 64, more than two padding characters, or an invalid character among the padding characters
Although if you use the site to translate base64 to image convert normally.
https://codebeautify.org/base64-to-image-converter
If you need an example base64 code write, I will give. It's just very big. I can give, for example, the beginning and the end of the code, according to my definition it is suitable or not. Well, in general, if you need an example, I will give. I do not understand why c # does not convert.
the second picture for which the method did not fit:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAtAC0AAD//gBRRmlsZSBzb3VyY2U6IGh0dHA6Ly9jb21tb25zLndpa2ltZWRpYS5vcmcvd2lraS9GaWxlOlZ3LXNjaXJvY2NvLW1vZGVsbC0yMDEwLmpwZ//bAEMABgQFBgUEBgYFBgcHBggKEAoKCQkKFA4PDBAXFBgYFxQWFhodJR8aGyMcFhYgLCAjJicpKikZHy0wLSgwJSgpKP/bAEMBBwcHCggKEwoKEygaFhooKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKP/AABEIAKUA3AMBIgACEQEDEQH/xAAdAAABB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JwBzZAG etAWVu7BAIJBHrSMAbflJPqelWOUAYB gpimTkswOflRSHbK7R xhuZcjG2xFCyRhs z0zkGrQjz0PXYbUwi/z0p0Kyv3fLuqYyMj4VH9lUnLFh4kHx9avNEh5SwHMpyCNsUxxsM5zvscUahsU 5VQCNuhx1yBQmNChHIQpGdvM1bKDP3SAaSxqB7W/jv8AnTSFZUCoGUAvtsPDPnmkQDgq3jsDVnkwMKcbZJzQEH3j1z4LVCsgdDyjcnxIU4 uah7rP 8/suR W1XHBCllGWHTOBUDvynHsj45pisyQh5ZpYyVIQKfdAyG8KiidJLoRPEhKg 1656jypUq5LZrXRce3jAU 0WwWO/kSKGaNYy7ADAXOMUqVNSdjcVVkwhUWzSsAQhG2MZBz4/KojEhRmCrjlyBjpk0qVGzFSEsK8xzjHMVHp/nFBOgQIMKSzlc4pUqpSYqQUkHsLytgnxKg7ZXp9aL7PvgORkdcdMGlSqrECYsMPaO fCm7hSV9c9fClSpoQlHMuBt1P0pih5iQ2D4bdKVKkxiAwAdsjxx60A3OPxpUqBgkkEYx9KZkICgtnP76VKnYhBjjqdt/wAadckjJPWlSp xDY6eR3piABkDptSpUAPjrv5UOfbYeWAM/ClSqvQhAZ32pjtSpUIQzpuRnw8RVdkBPRcdB7NKlQyl2f/Z
And the first picture has a very big base64 line, is it also off?
The problem seem originated from this line:
byte[] picture = Convert.FromBase64String(base64img);
If the base64img contains some header like data:image/png;base64, then Convert.FromBase64String() fails because the string is not fully formatted in Base64 format. Consider using string.Split() before converting from string parameter to remove corresponding Base64 header:
[HttpPost]
public ActionResult LoadImage(Car car, string base64img)
{
// split the header and content, separated by comma
var base64arr = base64img.Split(',');
byte[] picture = Convert.FromBase64String(base64arr[1]);
// do something with the image
return View();
}
If the content string contains characters other than ASCII or trailing padding ones, you should remove them like this:
string base64str = base64arr[1];
string processed = base64str.Replace('_', '/').Replace('-', '+');
switch (base64str.Length % 4)
{
case 2:
processed += "==";
break;
case 3:
processed += "=";
break;
}
byte[] picture = Convert.FromBase64String(processed);
Also consider using FormData object when passing image formatted with Base64 string:
$('#modalWindow').on('click', '#send', function () {
var file = $('#autoPicture').attr('src');
// note: if you send other form data, use 'serializeArray()' or 'serialize()'
var formData = new FormData();
// append other form contents here
formData.append("base64img", file);
$.ajax({
type: "POST",
url: "/Home/LoadImage",
data: formData,
success: function (data) {
alert('Привет');
},
error: function (error) {
alert(error.responseText);
}
});
});
Note:
The equals sign like = or == at the end of Base64 encoded string serves as trailing padding characters and not all Base64 encoded strings ended with them. You can see the reason behind padding here.

jQuery Selector escaping colon ":" works in IE but does not work elsewhere

I have an XSL object. I want to extract a select group of nodes. Another person or team wrote the XSL document and the line of code which selects those nodes, but it only works in IE and I'm trying to make it cross-browser compatible.
XSL file
<!-- snippet of XSL file -->
<xsl:variable name="title">aaa</xsl:variable>
<xsl:variable name="col1">CSV00001</xsl:variable>
<xsl:variable name="col2">CSV00002</xsl:variable>
<xsl:variable name="col3">CSV00003</xsl:variable>
<xsl:variable name="col4">CSV00004</xsl:variable>
<xsl:variable name="col5">CSV00005</xsl:variable>
<xsl:variable name="col6">CSV00006</xsl:variable>
<xsl:variable name="col7">CSV00007</xsl:variable>
<xsl:variable name="col8">CSV00008</xsl:variable>
<xsl:variable name="col9">CSV00009</xsl:variable>
JS file
// Extract title and column nodes
var varNodes = $(csvXsl).find("xsl\\:variable");
I tried referencing this article for ideas, Handling a colon in an element ID in a CSS selector, but that is for CSS. But I did attempt to replace the \: with the \\3A, \\3a, 3a, 3A and none of those worked.
Any suggestions?
As requested, here is a litle more info on how the XSL object gets created.
function loadXml(xmlFilePath) {
var retObj = null ;
var timeUniq = (new Date()).getTime();
// check protocol
var protocol = document.location.protocol;
if(protocol.toLowerCase().indexOf("http")>=0){
$.ajax({
url: xmlFilePath + "?t=" + timeUniq,
type: 'get',
dataType: 'xml',
async: false,
timeout: 1000
})
.done(
function(xml, status){
if( status != 'success' ){
return;
}
retObj = xml;
})
.fail(
function(xhr, textStatus){
return;
});
}
return retObj;
}
csvXsl = loadXml("./xsl/OrderListCSV.xsl");
Thank you.
Update
As requested, I have added a fiddle.
http://jsfiddle.net/Q3jNN/
Update2
Working JSFiddle routine with all the credit to commentator Niet.
http://jsfiddle.net/dNDN6/2/
In case the link is broken, here is the relevant portion:
// Workaround for JQuery bug, primarily using Vanilla JS.
function serializeXmlNode(xmlNode) {
if (typeof window.XMLSerializer != "undefined") {
return (new window.XMLSerializer()).serializeToString(xmlNode);
} else if (typeof xmlNode.xml != "undefined") {
return xmlNode.xml;
}
return "";
}
var tmpStr = serializeXmlNode(csvXsl); // Converts XML/XSL object to String
var tmp = document.createElement('div');
tmp.innerHTML = csvXsl; // Does not work
tmp.innerHTML = tmpStr; // This one works, had to serialize object first
var varNodes = tmp.getElementsByTagName('xsl\:variable'); // Works
var varNodes2 = tmp.getElementsByTagName('xsl:variable'); // Also works
I would do a number of steps to debug this issue:
Check the content of the csvXls variable, you can try for example to look for:
console.log(csvXsl) then
$(csvXsl).find("xsl\\:variable");
or $("xsl\\:variable",csvXsl);
If that variable contains the correct nodes, for example <xsl:variable name="col9">CSV00009</xsl:variable> then it could be a bug in jQuery, which I feel to exclude in such a basic selector.
Post how do you get the csvXsl with a bit more context, so we can help you better.
This is indeed a bug in jQuery.
Try using Vanilla JS instead:
var tmp = document.createElement('div');
tmp.innerHTML = csvXsl;
var varNodes = tmp.getElementsByTagName('xsl:variable');
must comment by 'Answer' since not enough reps
the line:
var inputTag = $("#test\\:1").val());
in the fiddle supposedly showing what works : http://jsfiddle.net/dNDN6/2/
actually does not work in Chrome / webkit
the correct method is to use plain JS and getElementsByTagName first on the tag without the namespace (after the colon) and if no element then the full tag like so:
var x = xmlDoc.getElementsByTagName("variable");
if (!x[0]) x = xmlDoc.getElementsByTagName('xsl:variable');
x will contain your array [cross-browser]

Php unlink() returning errors with encoded filepaths containing spaces

I'm trying to delete images by unlinking them via an AJAX function which encodes the filepath using encodeURIComponent before passing it.However, i am getting errors while unlinking them so i've done a bit of nosing around trying to find the error.
When i'm passing a file path with a space in it(e.g .../test/test item.jpg)
i get the error
PHP Warning: unlink(): Invalid argument in ...//file location
However when i pass a filepath with no spaces in it (e.g ../test/testitem.jpg), i do not get any errors.Why am i getting an invalid argument when i pass an encoded filepath with spaces in it?I thought that by encoding it with encodeURIComponent, the spaces in the filepath should have been encoded and taken care of?
I've tried calling the functions without encoding, and i still only get the invalid argument error when the file path contains spaces in them.How would/should i handle the spaces in the filepaths?
My function:
function DeleteImageDP(){
var itemid=$('#DisplayDeleteItemID').val();
var file=$('#DisplayDeleteFilePath').val();
var filepath=encodeURIComponent(file);
var itempicid=$('#DisplayDeleteItemPicID').val();
var cfm=confirm("Confirm deletion of picture? ( Note: Picture wil be deleted permanently.");
if(cfm == true)
{
$.ajax({
url:"delete/deletedp.php",
type:"POST",
data:"ItemID="+itemid+"&FilePath="+filepath+"&ItemPicID="+itempicid,
success:function(){
alert("Image successfully deleted.");
$('#ImagePreviewDP').prop('src','').hide();
$('#ImagePreviewDPValidate').val('');
$('#DisplayDelete').hide();
$('#ItemDetailsContainer').trigger('change');
},
error:function(){
alert("Image could not be deleted due to an error.");
}
});
return true;
}
else
{
return false;
}
};
Edit:PHP Code
$bizid=$_SESSION['BizID'];
$itemid=$_POST['ItemID'];
$file=$_POST['FilePath'];
$filepath=realpath('..\\'.$file);
$itempicid=$_POST['ItemPicID'];
//empties dp field in items table
$delete=$cxn->prepare("UPDATE `Items` SET `ItemDP`=:deleted WHERE `BusinessID`=:bizid AND `ItemID`=:itemid");
$delete->bindValue(":bizid",$bizid);
$delete->bindValue(":itemid",$itemid);
$delete->bindValue(":deleted","NULL");
$delete->execute();
//removes from itempics
$deletepic=$cxn->prepare("DELETE FROM `ItemPics` WHERE `BusinessID`=:bizid AND `ItemID`=:itemid AND `ItemPicID`=:itempicid AND `FilePath` LIKE :search");
$deletepic->bindValue(":search","%DP");
$deletepic->bindValue(":bizid",$bizid);
$deletepic->bindValue(":itemid",$itemid);
$deletepic->bindValue(":itempicid",$itempicid);
$deletepic->execute();
if($deletepic)
{
unlink($filepath);<--- This is the line returning the error
return ( true );
}
else
{
return ( false );
}
The interval is something like a special char in the file names.
You need to escape it in order to operate with the file.
Try this
$filepath = str_replace(" ", "\ ", $filepath);
unlink($filepath);
I just had similar problem and this is what works for me
unlink(urldecode($filepath));
for more info on urldecode read this article: http://php.net/manual/en/function.urldecode.php

Categories

Resources