How to pass dataTable arrays to php using ajax

How to pass dataTable arrays to php using ajax

eloginkoeloginko Posts: 6Questions: 4Answers: 0
edited July 2014 in Free community support

I want to pass the array's values from the dataTable to php in order to save array values to the database.

My problem is I'm having trouble passing the values of the array on the dataTable to php using ajax.

Basically I want to save all the content of the dataTable array in a database but i cant make it work can anyone help me please.

Script:

```$(document).ready(function(){
var dataSet;
try{
dataSet = JSON.parse(localStorage.getItem('dataSet')) || [];
} catch (err) {
dataSet = [];
}
$('#iTable').dataTable({
"data": [],
"columns": [{
"title": "Name"
}, {
"title": "Age"
}, {
"title": "Gender"
}, {
"title": "Action"
}],
"bStateSave": true,
"stateSave": true,
"bPaginate": false,
"bLengthChange": false,
"bFilter": false,
"bInfo": false,
"bAutoWidth": false
});
oTable = $('#iTable').DataTable();
for (var i = 0; i < dataSet.length; i++) {
oTable.row.add(dataSet[i]).draw();
}
$('#tAdd').click(function () {
var data = [
$('#tname').val(),
$('#tage').val(),
$("[name='tgender']:checked").val(),
"<button class='idelete'>Delete</button>"
];
oTable.row.add(data).draw();
dataSet.push(data);
localStorage.setItem('dataSet', JSON.stringify(dataSet));
});
$(document).on('click', '.idelete', function () {
var row = $(this).closest('tr');
oTable.row(row).remove().draw();
var rowElements = row.find("td");
for (var i = 0; i < dataSet.length; i++) {
var equals = true;
for (var j = 0; j < 3; j++) {
if (dataSet[i][j] != rowElements[j].innerHTML) {
equals = false;
break;
}
}
if (equals) {
dataSet.splice(i, 1);
break;
}
}
localStorage.setItem('dataSet', JSON.stringify(dataSet));
});
$('#tSave').click(function(){
$.ajax({
type: "POST",
url: "saveTable.php",
data: { tableArray : dataSet },
success: function(result) {

       }
    }); 
});

});```

saveTable.php

```<?php

error_reporting(-1);
ini_set('display_errors', 'On');

$host = "localhost";
$user = "root";
$pass = "";
$db = "test";

$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$myArray = $_REQUEST['tableArray'];
$pieces = explode(",", $myArray);

$sql = "INSERT INTO viewTables (name, age, gender, action) VALUES (:name, :age, :gender, :action)";
$query = $dbc->prepare($sql);
foreach ($pieces as $last) {
$query -> execute(array(':name'=>$name, ':age'=>$email, ':gender'=>$gender, ':action'=>$last));
}

<?php >``` ?>
This discussion has been closed.