Pass entire table data to action method using Jquery - javascript

This question might be dumb but since i am new to JS and Jquery i have been struggling to get it done.
I have a table in a page where user can edit cell values in place(I am using contenteditable attribute).
There is a Save All button, on click on which I want to send current values in all the rows of the table to server side action method.
Please suggest me on how to achieve this or a better way of achieving the same functionality.

When the Save All button is clicked, you can do something like this:
$("#saveAllBtnId").click ( function () {
// read the data from the table using loop
$('#myTable > tbody > tr').each(function() {
// here retrieve the values from the table cells
// Example
var cellValue = $(this).... // you need to fill this code as per your table structure
// store all the data in an array
var mydata = new Array ( cellValue, ....);
var jsonData = JSON.stringify(mydata);
// send the data to backend, e.g.
$.post ("back/end/code", { data : jsonData }, function () {});
});
});

Thanks a lot. This is what i wanted. However, a little modification was needed while creating array.Below is the working code.
function btnClicked() {
// read the data from the table using loop
var mydata = [];
$('#testTable > tbody > tr').each(function() {
// here retrieve the values from the table cells
// Example
var name = ($(this).find(".name").html());
var age = ($(this).find(".age").html());
var obj = { name: name, age: age };
// store all the data in an array
mydata.push(obj);
});
var jsonData = JSON.stringify(mydata);
// send the data to backend, e.g.
//for now adding an alert
for (var i = 0 ; i < mydata.length; i++) {
alert(mydata[i].name + mydata[i].age);
}
$.post ("Test/SomeAction", { data : jsonData }, function () {});
}

Related

I want to store Ids in data base column

I have data table with check box when I select multiple rows I get ids. When I select 2 rows the output is like this 2,3 in alert box I want to store the ids in one data base column
This is My code:
$('#create_challan').click(function () {
//alert('Dispatch Challan submit');
var allVals = [];
var saleid = [];
/*var buttonp = $(this);
buttonp.addClass('disabled');
buttonp.text("Working");*/
$('input[name=selectedBilties]:checked').each(function() {
allVals.push($(this).val());
saleid.push($(this).attr('saleid'));
});
alert(allVals);
function allAreEqual(aarray){
if(!aarray.length) return false;
return aarray.reduce(function(a, b){return (a === b)?a:(!b);}) === aarray[0];
}
How can I Store that ids in database.
You can store it via ajax send those ids to other page and get it via server side language(php, .net etc), and execute query
$.post("pagename", { "id": id,.....}, function (response) {
});

How can i Access the table added in Word or Excel and iterate throght each and every row and cell using Office.js

Is it possible to iterate through table rows and column after it is added in the document or worksheet.
I am using the following code to add a table and I want on the success of this code i should be able to access the rows and column should be able to replace the values of cells after some conversion. Bellow is the code that i am using to create the table.
var tableData = new Office.TableData();
var headers = [placeholder.columns.map(function (c) { return c.column; })];
tableData.headers = headers
tableData.rows = rows;
var document = Office.context.document;
document.setSelectedDataAsync(tableData, function (result) {
var placeholder = Office.context.document.settings.get(results.binding.id);
if (officeCallSucceded(result, true)) {
document.bindings.addFromSelectionAsync(Office.BindingType.Table, function (result) {
if (officeCallSucceded(result)) {
//SOME LOGIC FOR BINDING HERE TO ADD //EVENT handlers to the table just added
}
});
}
}
);
}
Yes, here's the code to retrieve any individual row of a Table in Excel:
Excel.run(function (ctx) {
// substitute 'Table1' with the table you want and '0' with your row index
var myRow = ctx.workbook.tables.getItem('Table1').rows.getItemAt(0);
myRow.load('values');
return ctx.sync().then(function() {
console.log(myRow.values);
});
});
To replace content in a row:
Excel.run(function (ctx) {
var myNewRow = [["a", "b", "c"]];
// substitute 'Table1' with the table you want and '0' with your row
var row = ctx.workbook.tables.getItem('Table1').rows.getItemAt(0);
row.values = myNewRow;
return ctx.sync();
});
In Word there's a similar TableRowCollection.getItem method, but it's still in preview: https://github.com/OfficeDev/office-js-docs/blob/WordJs_1.3_Openspec/word/resources/tablerowcollection.md#getitemindex-number

Inner function does not assign value to element dynamically created by outer function in jQuery

I am trying to create a search result dynamically added below the form through ajax call using parameter given in the form. I can add results using a table, but in these results I have client ids where I need Name, so I again use ajax call for each client id which return success but can not assign the values to corresponding table field. Below is my code, what is wrong here?
var stopMulti = 0;
$('#salesreport-end_date').change(function(){
var endDate = $(this).val();
var startDate = $('#salesreport-start_date').val();
var param = startDate+'#'+endDate+'#date';
if(stopMulti == 0){
$.get('index.php?r=reports/sales-report/sales-report',{ id : param }, function(data){
var sReport = JSON.parse(data);
if(typeof sReport != 'undefined'){
if(sReport.length != 0){
$('<div id="sales-report-div-1" class="col-sm-12"><h2 id ="sales-report-heading-1">Sales Report</h2></div>').insertAfter('#sub-button-div');
$('<table class="table-bordered text-center col-sm-12"><tr id="sales-report-row-head"><th class="text-center">Invoice Number</th><th class="text-center">Client Name</th><th class="text-center">Company Name</th><th class="text-center">Phone</th><th class="text-center">Net Total</th><th class="text-center">VAT</th><th class="text-center">Total</th></tr></table>').insertAfter('#sales-report-heading-1');
$('<br><br>').insertAfter('#sales-report-div-1');
var count = 0;
for(var i = 0; i < sReport.length; i++){
$('<tr><td id=sales-report-col-1'+count+'></td><td id=sales-report-col-2'+count+'></td><td id=sales-report-col-3'+count+'></td><td id=sales-report-col-4'+count+'></td><td id=sales-report-col-5'+count+'><td id=sales-report-col-6'+count+'></td><td id=sales-report-col-7'+count+'></td></tr></div>').insertAfter('#sales-report-row-head');
$('#sales-report-col-1'+count).html(sReport[i].invoice_id);
$.get('index.php?r=reports/sales-report/get-client',{ id : sReport[i].client_id}, function(client){
var client = JSON.parse(client);
$('#sales-report-col-2'+count).text(client.client_name);
$('#sales-report-col-3'+count).text(client.company_name);
$('#sales-report-col-4'+count).text(client.telephon);
});
$('#sales-report-col-5'+count).html(sReport[i].sub_total);
$('#sales-report-col-6'+count).html(sReport[i].taxrate);
$('#sales-report-col-7'+count).html(sReport[i].invoice_total);
count++;
}
}
}
});
}
stopMulti = 1;
});
That is I am getting blank fields for client name, company name and telephone.
Firebug does not find any error in the code.
The $.get callback function will be called asynchronously, and therefor any value like count will be changed before the .get returns.
A simple technique to overcome this is to use anonymous function, so your function should look like this:
for(var i = 0; i < sReport.length; i++)
{
f = function(i,count)
{
... rest of your code
}
f(i,count);
count++;
}
Here is a general example: https://jsfiddle.net/BentalSW/auyLq7rp/
You can't use count inside the inner AJAX Callback because by the time those asynchronous calls complete count will equal sReport.length and the wrong divs will be updated.
Use a .forEach loop instead of the for loop:
sReport.forEach(function(report, count) {
...
});
This will give you a value of count that is correctly bound to the current iteration count.
NB: it shouldn't be necessary to call JSON.parse on data that's already in JSON format - jQuery will do that for you automatically.

Format returned table data in json

I'm fairly new to javascript. I retreive data from a sql server database that looks like this :
[Object { shortcode="0013A2004031AC9A", latest_measurement=1067, keyid="6801"},
Object { shortcode="0013A2004031AC9A", latest_measurement=7, keyid="6802"},
Object { shortcode="0013A2004031AC9A", latest_measurement=8598838, keyid="6803"}]
I want to format this in a json like this :
{mac : 0013A2004031AC9A, keys : {6801:1067, 6802:7, 6803:8598838}}
but I just don't get to that.
I have
var jsonDataPerMac = {};
I loop over the json object above and for every new mac I find I do :
jsonDataPerMac[i]={"mac": device.shortcode, "keys":[]};
but how do I get to fill the keys?
Any hints would be appreciated.enter code here
var macs = [];
var jsonDataPerMac = {};
var i = 0;
$.ajax({
url: "/bmmeasurements",
type: "GET",
data: {"unitid" : unitid},
async: false,
success: function (data) {
console.log(data);
initializeTable();
$.each(data, function (index,device) {
//add all distinct macs in an array, to use them as a column header
if($.inArray(device.shortcode, macs) == -1) {
macs.push(device.shortcode);
jsonDataPerMac[i]={"mac": device.shortcode, "keys":[]};
i++;
//create a table cell for each possible key. id = 'mac-key'
createTableGrid(device.shortcode);
}
//add the measurement data to the correct cell in the grid
$('#' + device.shortcode + '-' + device.keyid).html(device.latest_measurement);
});
}});
Here is my proposition. I would rather avoid using jQuery to perform such a simple operations. In this particular example, we use forEach and for..in loop.
//new output array
var newArray = [];
//we traverse the array received from AJAX call
array.forEach(function(el) {
var added = false; // it's false by default
// we check if the mac is already in newArray, if yes - just add the key
for(var i in newArray) {
if(newArray[i].mac == el.shortcode) {
newArray[i].keys.push(el.keyid+":"+el.latest_measurement);
added = true; // tells us whether the key has been added or not
}
}
// if key hasn't been added - create a new entry
if(!added) {
newArray.push({"mac": el.shortcode, "keys":[el.keyid+":"+el.latest_measurement]});
}
});
console.log(newArray);
You can transform above code to a function and then, reuse it in your ajax onSuccess method. Remember to pass the array as an argument and to return newArray.
JSFiddle:
http://jsfiddle.net/2d5Vq/2/
You need to combine the entries first...
var reducedData = {};
$.each(macs, function(index,macitem){
if (reducedData.hasOwnProperty(macitem.shortcode)) {
reducedData[macitem.shortcode].push(macitem.key);
} else {
reducedData[macitem.shortcode] = [ macitem.key ];
}
});
And then map to your desired format inside an array...
var jsonDataPerMac = [],
i = 0;
$.map(reducedData, function(keys,mac){
jsonDataPerMac[i++] = {"mac": mac, "keys": keys};
// your other code goes here
});
Also your usage of jsonDataPerMac suggests that you want it to be an array.

How to serialize delete data with jqGrid, multiselection, and Spring?

Currently, I have an overridden delGridRow call that looks like this (credit to Krams and his Spring tutorial):
var row = $('#grid').jqGrid('getGridParam','selrow');
$('#grid').jqGrid( 'delGridRow', row,
{ url:'deleteRequirement.html',
recreateForm: true,
beforeShowForm: function(form) {
//Change title
$(".delmsg").replaceWith('<span style="white-space: pre;">' +
'Delete selected record?' + '</span>');
//hide arrows
$('#pData').hide();
$('#nData').hide();
},
reloadAfterSubmit:true,
closeAfterDelete: true,
serializeDelData: function (postdata) {
var rowdata = $('#grid').getRowData(postdata.id);
// append postdata with any information
return {id: postdata.id, oper: postdata.oper, reqID: rowdata.reqID};
},
afterSubmit : function(response, postdata)
{
var result = eval('(' + response.responseText + ')');
var errors = "";
if (result.success == false) {
for (var i = 0; i < result.message.length; i++) {
errors += result.message[i] + "<br/>";
}
} else {
$('#msgbox').text('Entry has been deleted successfully');
$('#msgbox').dialog(
{ title: 'Success',
modal: true,
buttons: {"Ok": function() {
$(this).dialog("close");
}
}
});
}
// only used for adding new records
var newId = null;
return [result.success, errors, newId];
}
});
else {
$('#msgbox').text('You must select a record first!');
$('#msgbox').dialog(
{ title: 'Error',
modal: true,
buttons: {"Ok": function() {
$(this).dialog("close");}
}
});
}
In order to add support for multiselection deletes, I changed the "selrow" first line to this:
var rowList = jQuery("#grid").getGridParam('selarrrow');
After this, things start getting sketchy fast. The spec says that the default delGridRow can accept an array of inputs records to delete. I made the following change to attempt to get the new 'rowList' variable to get used:
$('#grid').jqGrid( 'delGridRow', rowList, ...
I'm still hitting my deleteRequirement.html URL in my Spring controller, but only the last records appears to make it. I'm guessing the problem is in the postdata preparation in the serializeDelData section, but I haven't found the correct way to prepare this postdata with the list of records instead of the single record.
Any suggestions/insight would be appreciated.
Thanks all.
I don't use Spring myself, but some parts of your code seams be strange for me.
First of all the you can use two forms of the first parameter of delGridRow (row in your code). It can be either the comma-separated list of ids or an array of ids. If you use array of ids then jqGrid convert it to the comma-separated format by rowids = rowids.join();. As the result the format of postdata.id inside of serializeDelData can be also the comma-separated list of ids.
So if you need to support delete of multiple rows you should
modify the code of serializeDelData to send in reqID property also the list of the reqID. The corresponding code can be
serializeDelData: function (postdata) {
var ids = postdata.id.split(','), i, l = ids.length, reqIDList = [];
for (i = 0; i < l; i++) {
reqIDList.push($(this).jqGrid("getCell", ids[i], "reqID"));
}
return {id: postdata.id, oper: postdata.oper, reqID: reqIDList.join()};
}
modify your server code to support both id and reqID in comma-separated form.
Inside of afterSubmit callback you you the lines
// only used for adding new records
var newId = null;
return [result.success, errors, newId];
You can modify the lines to the following
return [result.success, errors];
because only the first two elements of the array returned by afterSubmit callback will be used.

Categories

Resources