Invalid JSON retrived from PHP script after form submit
Invalid JSON retrived from PHP script after form submit
The page has a form which is submitted after some button is clicked, and executes "result.php", a script returning a JSON string. The following JSON string printed by JSON.stringify(data):
"{\"data\": [{ \"code\":\"XXAA\",\"date\":\"2016/02/24\",\"time\":\"18:00\",\"value\":\"41\"},{\"code\":\"XXAB\",\"date\":\"2016/02/25\",\"time\":\"14:00\",\"value\":\"39\"}]}"
JavaScript code:
<script src="https://code.jquery.com/jquery-1.12.3.min.js" integrity="sha256-aaODHAgvwQW1bFOGXMeX+pC4PZIPsvn2h1sArYOhgXQ=" crossorigin="anonymous"></script>
<script type="text/javascript" src="//cdn.datatables.net/1.10.11/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(function() {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type : 'POST'
,url : 'result.php'
,data : $('form').serialize()
,success: function () {
}
})
.done(function(data) {
console.log(JSON.stringify(data));
$("#result").dataTable().fnDestroy();
$('#result').DataTable({
"processing": true,
"serverSide": true,
"ajax": data,
"columns": [
{ "data": "code" },
{ "data": "date" },
{ "data": "time" },
{ "data": "value" }
]
});
});
});
});
</script>
HTML code for table "result":
<table id="result" class="table table-condensed table-hover">
<thead>
<tr>
<th>Code</th>
<th>Date</th>
<th>Hour</th>
<th>Value</th>
</tr>
</thead>
</table>
Error is thrown: DataTables warning: table id=result - Ajax error.
When I check the response from the server using Chrome's debug, it shows the correct JSON: {"data": [{"code":"XXAA", (...)
Answers
"Corrected" by using array of arrays instead of array of objects and:
.done(function(data) {
$("#result").dataTable().fnDestroy();
var column_data = $.parseJSON(data);
if (column_data.length === 1) {
$('#result').dataTable().fnAddData(column_data);
}
for (var j=0;j<=column_data.length-1;++j){
$('#result').dataTable().fnAddData(column_data[j]);
}
});
I guess now I just need to use the same structure, but loop the array of objects instead.
An array of objects is perfectly valid.
It looks like there are two errors in the above code:
serverSide
enabled but are loading the data client-sideajax
option. Simply usedata
if you already have the data (i.e.data: data.data
in the case above sincedata
contains an object with a propertydata
which has the array).This second point is something I've seen a number of questions about recently. Is there something in the documentation that lead you to assign data to the
ajax
option? If so, can you tell me so I can change it.Allan