Submit() to send JSON format
Submit() to send JSON format
jsmith3
Posts: 19Questions: 4Answers: 0
Hello
I'm using the following code with hope the submit() function will send data in JSON format:
var table = $('#example').DataTable( {
ajax: {
url: "/api/customers",
contentType: "application/json",
type: "POST",
data: function ( d ) {
return JSON.stringify( d );
}
}
} );
Any ideas if this will work or is there a better way to do this?
This question has an accepted answers - jump to answer
This discussion has been closed.
Answers
Are you talking about using Editor's submit()? If so then do the same in the Editor's
ajax.data
option. There is an example in the docs.Kevin
Thank you!
It appears to send the correct data but its wrapped in a data field and I believe the id number eg:
{"data":{"3075":{"Username":"test","DisplayName":"test", Enabled":"1"}},"action":"edit"}
Is there a way I can strip the data/3075 part so its just sending the record data?
I thought just using return JSON.stringify( d.data ) or something similar but I'm not sure how to reference that integer index as it changes from record to record
OK I think I found a solution:
var z = JSON.parse(JSON.stringify(d.data));
var key = Object.keys(z);
return JSON.stringify( d.data[key[0]] );
Thanks for your help
I believe the number is Editor's unique ID for the row. Do you need this for your query to update the proper record?
Also you might need the
action
property so that you know if the row is being edited, removed or created. More info is in this doc regarding the expected client / server exchange with Editor.Editor supports multi-row editing. The data object could have multiple rows / multiple objects. If you want to only send
{"Username":"test","DisplayName":"test", Enabled":"1"}
then you will need to use Javascript methods to manipulate the object to contain what you want before usingJSON.stringify()
.If you want to support multi-row then you will want to loop through the objects in
data
andpush()
them onto an array that you useJSON.stringify()
with. Or use something like Object.keys(obj) to get the keys and iterate the resulting array.Kevin