How to pass dataTable array value to php using ajax
How to pass dataTable array value to php using ajax
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 in a database but i cant make it work can anyone help me please.
html:
Name:
<input type="text" name="tname" id="tname" />
<br />Age:
<input type="text" name="tage" id="tage" />
<br />Gender:
<br />
<input type="radio" name="tgender" value="Male" />Male
<br />
<input type="radio" name="tgender" value="Female" />Female
<br />
<button type="button" id="tAdd" name="tAdd">Add</button>
<table id="iTable" class="table table-striped table-bordered" cellspacing="0" width="100%"></table>
<button type="button" id="tSave" name="tSave">Save</button>
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(),
"Delete"
];
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));
}