Posting jquery datatable data to server in JSON format -


i know question has been asked numerous times on , on datatables site, cannot work using solutions provided.

i building datatable on client side , want post client data wep api controller in json format.

the client side working correctly when comes adding/deleting rows. when try create json using:

    var table = $('#detailtable').datatable(); var details = json.stringify(table.rows().data().toarray()); 

i getting following result:

[["11046","abc","bis","123","123",15129]] 

so missing column names in json object, web api failing pick , convert to:

list<receiptentryviewmodel> receiptdetails 

so how can datatables generate json in following format:

[["itemid":"11046","itemcode":"abc","itemname":"bis","price":"123","quantity":"123","total":15129]] 

if want collect column names , use them property names in json, can build array of column names way :

var fieldnames =  [], json = [] table.settings().columns()[0].foreach(function(index) {   fieldnames.push($(table.column(index).header()).text())   }) 

i using text() filter out html. above iterate on each row instead, , construct object literal (json item) each row using collected fieldnames :

table.rows().data().toarray().foreach(function(row) {   var item = {}   row.foreach(function(content, index) {      item[fieldnames[index]] = content   })   json.push(item) })   

now have valid json can stringify , send server.

small sample demo -> http://jsfiddle.net/5j9wgorj/

note example. if have larger datasets should avoid foreach , use for-loops instead. there should no need blindly rebuilding array of header names since you, developer, know both column names , want properties named beforehand.


update solution ended be. contortions building json can avoided if datatable prepared using json. define columns section :

var table = $('#example').datatable({   columns : [     {  data : 'myfield' }   ] }) 

and insert new rows json / literals :

table.row.add({ myfield: 'some value' }).draw() 

now

json.stringify( table.rows().data().toarray() ) 

will return valid json string can passed serverscript.

demo -> http://jsfiddle.net/d07f6uvf/


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -