Jquery exporting table to csv hidden table cells - javascript

I need to be able to export a HTML table to CSV. I found a snippet somewhere; it works but not entirely how I want it to.
In my table (in the fiddle) I have hidden fields, I just use quick n dirty inline styling and inline onclicks to swap between what you see.
What I want with the export is that it selects the table as currently displayed. so only the td's where style="display:table-cell". I know how to do this in normal JS.
document.querySelectorAll('td[style="display:table-cell"])');
but how can I do this using the code I have right now in the exportTableToCSV function?
(sorry but the text in the fiddle is in dutch as its a direct copy of the live version).
The fiddle:
http://jsfiddle.net/5hfcjkdh/

In your grabRow method you can filter out the hidden table cells using jQuery's :visible selector. Below is an example
function grabRow(i, row) {
var $row = $(row);
//for some reason $cols = $row.find('td') || $row.find('th') won't work...
//Added :visisble to ignore hidden ones
var $cols = $row.find('td:visible');
if (!$cols.length) $cols = $row.find('th:visible');
return $cols.map(grabCol)
.get().join(tmpColDelim);
}

Here's how i solved it. Decided to step away from a pure javascript solution to take processing stress off the client and instead handle it server side.
Because i already get the data from the database using a stored procedure i use this to just get the dataset again and convert it into an ViewExportModel so i have a TotalViewExport and a few trimmed variations (reuse most of them) based on a Selected variable i fill a different model.
Added to the excisting show function to update a Selected variable to keep track of the currently selected view.
When the user clicks Export table to excel it calls to the controller of the current page, IE. AlarmReport (so AlarmReportController) and i created the action ExportReports(int? SelectedView);
In addition i added CsvExport as a manager. This takes data results (so c# models/ iqueryables/ lists/ etc). and puts them into a Csv set. using the return type BinaryContent one can export a .csv file with this data.
The action ExportReports calls the stored procedure with the selectedview parameter. The result gets pumped into the correct model. this model is pumped into the CsvExport model as rows.
The filename is made based on the selected view + What object is selected + current date(yyyy-MM-dd). so for example "Total_Dolfinarium_2016-05-13". lets
lastly the action returns the .csv file as download using the BinaryContent Returntype and ExportToBytes from the CsvExport
The export part of this action is programmed like so(shortened to leave some checks out like multiple objects selected etc)(data and objectnames are gathred beforehand):
public ActionResult ExportCsv(CsvExport Data, string ObjectName, string Type){
var FileName = Type + "_" + ObjectName + "_" + DateTime.Now.ToString("yyyy/MM/dd");
return BinaryContent("text/csv", FileName + ".csv", Data.ExportToBytes());
}

Related

CKEditor Plug-In: Getting text of drop-down item

I created a plug-in for CKEditor that opens a dialog with a drop-down. In that drop-down is a list of files the user has uploaded outside of CKEditor. The plan is to insert a "tag" into the text containing that filename, something like [[myfile.pdf]] and then when I display the actual page, I will insert a link to that file.
The problem is that the drop-down box being created by CKEditor is listing the filename (properly) but when I select it, it inserts the file's SIZE into the text rather than the filename. When the plug-in runs, it does an ajax call and grabs a directory listing of the user's files, which is where that number comes from; I think it's confusing it with a file ID.
Here's the meat of the plug-in. I left out the ajax call for brevity. It populates the variable "items."
EDIT: I modified the results returned from the ajax call to just return the filename, and then to return the filename (twice) using two different column names (name and filename) and in both cases, the inserted value was NULL. It just doesn't want to insert a text value it seems.
I also tried changing the values of id: under contents and also under elements (alternately) between tab-basic and linkType, and I got an error in the JS console about cannot read property getValue of undefined. Curses, foiled again!
ANOTHER EDIT: I tried putting the names of the files in a database table and I return that to the plug-in instead of the directory listing. If I select filename, attachmentid (in that order), the OPTION box lists the attachmentid, and inserts the filename. If I select attatchmentid, filename it will do it the exact opposite. So then I thought, gee, what if I selected the filename twice? So I did select filename, filename as filename2. And it works! This still isn't an ideal solution so I'm hoping somebody will know the proper way to do it.
CKEDITOR.dialog.add('attachfileDialog',function(editor){
return {
title:'Attach File',
minWidth:400,
minHeight:200,
contents:[{
id:'tab-basic',
label:'Choose File',
elements:[{
type:'select',
id:'linkType',
label:'Choose File',
items:items,
'default':''
}]
}],
onOk:function(data){
var dialog = this;
var componentType = dialog.getValueOf('tab-basic','linkType');
var selectedText = editor.getSelection().getSelectedText();
if(componentType != ''){
editor.insertText('[[' + componentType + ']]');
}
}
};
});
I actually copied this from another plug-in and modified it to suit, so I'll admit I don't much know what I'm doing here. I've dug through the CKEditor docs but they aren't particularly helpful.
The variable componentType is coming back with the file size. I'm just not sure how to make it grab the text instead of the value; if you view the source, the has the value of the file size, and the text is the filename.
Any ideas? Thank you!

how to clear filtering, sorting and paging on a webdatagrid on client side?

I have a webdatagrid which retains data on searching in text box. I have noticed when I filter/page/sort the data and before clearing any of these I make a new search then the new search results retains previous filter/page/sort condition. I am not clearing it before reloading the page. I have search method on client side and I am using following code which does not work:
function btnSearch_click(sender, evntArgs){
var grid = $find('<%= grid1.ClientID %>');
grid.get_behaviors().get_filtering().clearColumnFilters();
grid.get_behaviors.get_sorting().clearColumnSorting();
grid.get_behaviors.get_paging().clearPaging();
}
This code is incorrect.
Since my grid loads on pressing the search button. I used the following on the server side:
if (search == "True")
{
var filtering = grid1.Behaviors.Filtering;
grid1.Behaviors.Sorting.SortedColumns.Clear();
grid1.Behaviors.Paging.PageIndex = 0;
grid1.Behaviors.Filtering.ClearBehaviorColumnInfo();
grid1.Behaviors.Filtering.ColumnFilters.Clear();
filtering.FilterType = Infragistics.Web.UI.GridControls.FilteringType.ExcelStyleFilter;
grid1.Behaviors.Filtering.ApplyFilter();
}
I wanted to implement excel style filter and Infragistics had no way to reproduce excel filter after clearing it I had to apply row type filter first and then change the filter type to excel type.

Save dynamic data created using createElement(Javascript) to database

I am new to this forum as well as webpage designing. I am trying to design a profile management tool using JSP in which there are dynamically added(through javascript createElement) input fields to which names are assigned. I am able to save only one record to database and others are ignored.
My question is how to save all the data that is dynamically added?
Please help me on this.
Javascript code:Using the below function, I am able to get Javascript array
function addedu()
{
$(document).ready(function(){
$(".ed").each(function(input){
var value = $(this).val();
var id = $(this).attr('id');
t= id+' : '+ value;
arr.push(t);
});
});
var newinput1 = document.createElement("input");
newinput1.name="i1"
newinput1.className="ed"
newinput1.id="Education"
newinput1.innerHTML = "";
document.getElementById('edu').appendChild(newinput1);
}
JSP code:
String edu1=request.getParameter("i1");
Statement st1=con.createStatement();
String sql1="insert into education values('"+pno+"','"+edu1+"');
st1.executeUpdate(sql1);
On the client side you can use jQuery to dynamically add rows and read necessary values. To access the rows of the table you can use jQuery selectors. Then save the data in the JavaScript array, convert it to JSON and send it to the server side.
Here is an example (with using PHP, but in this case it doesn't matter):
Store HTML Table Values in a Javascript Array and Send to a PHP Script Using jQuery and Ajax
On the server side you'll need to make a lot of inserts via plain JDBC, use BATCH insert instead of hitting database once for each insert statement.
Here is an example:
Java: Insert multiple rows into MySQL with PreparedStatement
If you'll decide to use Spring, here is an example:
How to Insert multiple rows from web form into database using java spring framework

jQuery Autofill textbox with information from another autofill

I am having an issue with jQuery autocomplete. Basically I have a search bar, and when you type in what you're looking for the jQuery code I have calls a php script which does a MySQL query and returns everything I need and fills in the text boxes accordingly. What I then want to do is take the value I receive from that autocomplete, and use it in another autocomplete to fill in more data. The tricky part is that the data I need to get with the 2nd query is located in a different table than the first query, which share a relationship. My question is do I need a completely separate function to do this, or can I simply put both queries in the 1 php script and have the information from the first query be used for my 2nd query.
Any help is appreciated thanks!
Here is the jQuery function:
$(function() {
/* $('#abbrev').val("");
*/
$("#q16_location16").autocomplete({
source: "location_query.php",
minLength: 1,
select: function(event, ui) {
$('#q16_location161').val(ui.item.LocationID);
$('#SystemName').val(ui.item.SystemName);
$('#SiteAddress1').val(ui.item.SiteAddress1);
$('#SiteAddress2').val(ui.item.SiteAddress2);
$('#SiteCPP').val(ui.item.SiteCPP);
$('#Contact').val(ui.item.Contact);
$('#SiteLocationHours').val(ui.item.SiteLocationHours);
}
});
});
and the php script:
/* If connection to database, run sql statement. */
if ($conn)
{
$fetch = mysql_query("
SELECT Location.LocationID,
Location.SystemName,
Location.SiteAddress1,
Location.SiteAddress2,
CONCAT_WS(' ', Location.SiteCity, Location.SiteProvince, Location.SitePostalCode) AS SiteCPP,
CONCAT_WS(' ', Location.ContactName, Location.ContactPhone, Location.ContactEmail) AS Contact,
Location.SiteLocationHours,
CONCAT_WS(' ', SystemName, SiteNameLocation, SiteAddress1, SiteCity, SiteProvince, SitePostalCode) as expr2
FROM Location
WHERE Location.SystemName like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SiteNameLocation like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SiteAddress1 like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SiteCity like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SiteProvince like '%".mysql_real_escape_string($_GET['term'])."%'
OR Location.SitePostalCode like '%".mysql_real_escape_string($_GET['term'])."% '
LIMIT 0,15");
/* Retrieve and store in array the results of the query.*/
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['LocationID'] = $row['LocationID'];
$row_array['value'] = $row['expr2'];
$row_array['SystemName'] = $row['SystemName'];
$row_array['SiteAddress1'] = $row['SiteAddress1'];
$row_array['SiteAddress2'] = $row['SiteAddress2'];
$row_array['SiteCPP'] = $row['SiteCPP'];
$row_array['Contact'] = $row['Contact'];
$row_array['SiteLocationHours'] = $row['SiteLocationHours'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
mysql_close($conn);
/* Toss back results as json encoded array. */
echo json_encode($return_arr, $return_arr2);
So when the user types in "New York" they can can select that option. In my example New York has an ID of 5. I also have a query that selects different streets in new york but this is in a separate table. in my streets table however, there is a "LocationID" column that for every street in new york will have a value of 5. So I want to take that ID of 5 when a user enters in new york and generate all the streets from a different table which also have that ID. I have tried multiple things in terms of creating a new function but I am just unsure of how I would pass that ID to the function.
Thanks
You can use one PHP script for this. Here's about what I'd think the basic structure will look like:
Pass two values to "location_query.php". The first value would be the name of the table that you want to query. The second value could be the selection result from the auto-complete text box.
Create a prepared statement in "location_query.php" from the two values that were passed to "location_query.php".
Perform your query.
JSON encode the result (just like you did before).
I'd also like to point out a security concern with your code. You should be using Mysqli and prepared statements instead of PHP's MySQL and mysql_real_escape_string. mysql_real_escape_string has been shown to have security deficiencies that can lead to security breaches and PHP's MySQL class has been deprecated. Mysqli and Prepared statements are much safer, and, in my opinion, provide for cleaner code since it allows for the separation of the SQL and the parameters.
Hope this helps!
EDIT: I think I understand what you're trying to do now, but I think there's a better way to go about doing it. Instead of assigning the id value to a hidden field and trying to have jquery detect every time that field is changed, I would just do the following:
For your first text box's select method:
select:function(event, ui) {
$.get("location_query.php", {
searchterm:$(ui).val()
}, yourFunction);
}
Here's an example implementation of "queryFinished":
function queryFinished(data, textStatus, jqXHR) {
var mJSON = $.parseJSON(data);
/* mJSON is the parsed JSON data returned from your "location_query.php"
script.*/
//TODO the rest of your code
}
Here's what's going on:
We define a custom function to be called when the first text box has a new item selected. This functions only purpose is to call a GET on "location_query.php".
Then, we pass the value of the selected field from the first text box via our GET call.
We then create a function to be called when GET returns.
Finally, we parse the encoded JSON that is returned by "location_query.php". After that, you can perform whatever tasks you need with the parsed JSON (mJSON in our example).
Taking this approach keeps us from having to worry about "listening" for a value change in our hidden ID field and makes everything nice and clean.

Django Dynamic Drop-down List from Database

I wanted to develop a Django app and one of the functionalities I'd like to have is dynamic drop-down lists...specifically for vehicle makes and models...selecting a specific make will update the models list with only the models that fall under that make....I know this is possible in javascript or jQuery (this would be my best choice if anyone has an answer) but I don't know how to go about it.
Also, I'd want the make, model, year and series to be common then the other attributes like color, transmission etc to be variables so that one needs only enter the make, model, year, and series only for a new vehicle. Any ideas would be highly appreciated.
The 3 things you mention being common, make, model, year, would be the 3 input values. When given to the server, an object containing the details would be returned to the calling page. That page would parse the object details (using JavaScript), and update the UI to display them to the user.
From the Django side, there needs to be the facilities to take the 3 inputs, and return the output. From the client-side, there needs to be the facilities to pass the 3 inputs to the server, and then appropriately parse the server's response.
There is a REST api framework for Django that makes it rather easy to add the "api" mentioned above -- Piston. Using Piston, you'd simply need to make a URL for that resource, and then add a handler to process it. (you'll still need to skim the Piston documentation, but this should give you an idea of what it looks like)
urls.py:
vehicle_details = Resource(handler=VehicleDetails)
url(r'^vehicle/(?<make>.*)/(?<model>.*)/(?<year\d{2,4}/(?P<emitter_format>[a-z]{1,4}), vehicle_details, name='vehicle_details'),
handler.py:
class VehicleDetails(BaseHandler):
methods_allowed = ('GET',)
model = Vehicles #whatever your Django vehicle model is
def read(self, request, *args, **kwargs):
# code to query the DB and select the options
# self.model.objects.filter()...
# Build a custom object or something to return
return custom_object
This simply sets up the url www.yoursite.com/vehicle/[make]/[model]/[year]/json to return a custom data object in JSON for jquery to parse.
On the client side, you could use jquery to setup an event (bind) so that when all 3 drop downs have a value selected, it will execute a $.get() to the api URL. When it gets this result back, it passes it into the Jquery JSON parser, and gives the custom object, as a javascript object. That object could then be used to populate more drop down menus.
(Big warning, I just wrote the following off the top of my head, so it's not meant to be copy and pasted. It's just for the general idea.)
<script type="text/javascript">
// On document load
$(function() {
$('#dropdown_make').bind('change', checkForValues());
$('#dropdown_model').bind('change', checkForValues());
$('#dropdown_year').bind('change', checkForValues());
});
function checkForValues() {
if ($('#dropdown_make').val() && $('#dropdown_model').val() && $('#dropdown_year').val())
updateOptions();
}
function updateOptions() {
url = '/vehicle/';
url += $('#dropdown_make').val() + '/';
url += $('#dropdown_model').val() + '/';
url += $('#dropdown_year').val() + '/';
url += 'json/';
$.get(url, function(){
// Custom data object will be returned here
})
}
</script>
This is uncanny: Dynamic Filtered Drop-Down Choice Fields With Django
His question:
"Here is the situation: I have a database with car makes and models. When a user selects a make, I want to update the models drop-down with only the models associated with that make. ... Therefore I want to use Ajax to populate the data."
You're not the same guy? :)

Categories

Resources