0

While trying to render a datatable with ajax sourced data, I get a

400 bad request

as ajax response.

The Json I get from the ajax call is as below which is happily validated by Jsonlint

{
    "data": {
        "title": "Seminar",
        "pdate": "2016-02-05",
        "duedate": "2016-03-04"
    }
}

I am using the following javascript suggested by datatables for rendering ajax sourced data ;

$('#table1').DataTable({
    ajax: {
        url: '?r=site/test',
        type: 'POST',
        dataSrc: 'data'
    },
    columns: [
        { data: 'title' },
        { data: 'pdate' },
        { data: 'duedate' }
    ]
});

Here is the fiddle.

$b = [
'title'=>  "Seminar",
'pdate'=>  "2016-02-05",
'duedate' => "2016-03-04"

];

$a['data'][] = $b;
echo json_encode($a);

What's wrong ?

0

1 Answer 1

1

data has to be an array of "rows"

From the documentation:

The main data source used for a DataTable must always be an array (it is created automatically when using DOM sourced data). Each item in that array will define a row to be displayed and DataTables can use three basic Javascript data types as the data source for the rows

  • Arrays - []
  • Objects - {}
  • Instances - new MyClass()

Hence the returned data from ?r=site/test has to be

{
    "data": [{
        "title": "Seminar",
        "pdate": "2016-02-05",
        "duedate": "2016-03-04"
    }]
}

fiddle

Sign up to request clarification or add additional context in comments.

4 Comments

can you kindly add a mock json response to the fiddle ?
just added to the question, the php code I'm using for the json request. Kindly check .
jsfiddle.net/j6uozv9j works, but when I echo the same through JSON, it gives 400 bad request error.
The fiddle in my answer uses /echo/json/ which returns whatever you're passing in as data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.