sruthi sripathi sruthi sripathi - 11 months ago 62
Javascript Question

How to post data of selected rows of a dataTable to php controller through an JQuery ajax call

I used this code from to select multiple rows

$('#table tbody').on('click','tr', function(){

This is the initialization for jquery datatable

$(document).ready(function() {

table = $('#table').DataTable({

"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.

dom: 'Bfrtip',
buttons: [
//'copyHTML5', 'csvHTML5', 'excelHTML5', 'pdfHTML5', 'printHTML5'
'copy', 'csv', 'print'//, 'excel', 'pdf'
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('person/ajax_list')?>",
"type": "POST"

//Set column definition initialisation properties.
"columnDefs": [
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
"targets": [ -2 ], //2 last column (photo)
"orderable": false, //set not orderable


$('#table tbody').on('click','tr', function(){

Now I want to send these selected rows to php controller through an ajax call so I can then create a csv file with these selected rows data.

I created a button which on click calls the following function where the ajax call is made

function create_PO()

var url = "<?php echo site_url('person/create_csv')?>";
var selectedData = table.rows('.selected').data();
newData = new Array();
jsonData = JSON.stringify({data : (selectedData[0].slice(0,5))});
//newData = $.serialize(newData);

url : url,
type: "POST",
data: jsonData,
contentType: false,
processData: false,
dataType: "JSON",
success: function(data)
// alert("sheet created successfully");

// $('#btnSel').text('create');
// $('#btnSel').attr('disabled',false);

/*error: function (jqXHR, textStatus, errorThrown)
alert('Error creating file');



when I do
from the controller, the response is showing empty array.
Also, the
function in success option of ajax is also not printing anything. Can anybody pls tell me what the problem is? Thanks!

Answer Source

JQuery part

The reason you are not getting anything in console, is that success callback gets the data that is returned by server, not the data which is sent. Try console.log(jsonData).

Also, to analyze sent data, use Network tab on Chrome Developer Tools.


On the PHP side, you might be passing data in request payload, thats because your form is type of JSON, not Content-Type: application/x-www-form-urlencoded

To access it use the following instead of $_POST:

$data = file_get_contents('php://input');

Process JSON

To process your stringified json to array:

$processedData = json_decode($data);

now you can access your array properties like this:

foreach($processedData as $item){
        // do stuff
        echo $item;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download