Save created row in datatable editor via php - javascript

I using datatable editor to display rows
This is the code i'm using
var editor;
$(document).ready( function () {
editor = new $.fn.dataTable.Editor( {
"ajaxUrl": {
"create": "admin/save",
},
"domTable": "#example",
"fields": [ {
"label": "username:",
"name": "username"
}, {
"label": "password:",
"name": "password",
"type":"password"
}, {
"label": "fname:",
"name": "fname"
}, {
"label": "lname:",
"name": "lname"
}, {
"label": "email:",
"name": "email"
},{
"label": "address:",
"name": "address"
}
]
} );
$('#example').dataTable( {
"sDom": "Tfrtip",
"aoColumns": [
{ "mData": "username"},
{ "mData": "password" },
{ "mData": "fname" },
{ "mData": "lname" },
{ "mData": "email" },
{ "mData": "address" }
],
"oTableTools": {
"sRowSelect": "single",
"aButtons": [
{ "sExtends": "editor_create", "editor": editor },
{ "sExtends": "editor_edit", "editor": editor },
{ "sExtends": "editor_remove", "editor": editor }
]
}
} );
} );
How can I pass the form data to controller page.I also given name field but it is not added to element.
create : admin/save
Here admin is the controller name and save is the action name.
Please help me.

Using Datatables with the Editor extension, it sends data to the server to be processed. The client sends three fields: action, id and data. The action can be create, edit or delete. The id is only filled in for edit.
So in short, you can use this controller:
<?php
namespace MyModule\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
class DatatablesController extends AbstractActionController
{
public function saveAction()
{
if (!$this->getRequest()->isPost()) {
$response = $this->getResponse();
$response->setStatusCode(405); // Method not allowed
return $response;
}
$action = $this->params()->fromPost('action', null);
$data = array();
switch ($action) {
case 'create':
$data = $this->createRow();
break;
case 'edit':
$data = $this->editRow();
break;
case 'delete':
$data = $this->deleteRow();
break;
default:
$response = $this->getResponse();
$response->setStatusCode(422); // Unprocessable entity
return $response;
}
$model = new JsonModel($data);
return $model;
}
protected function createRow()
{
$data = $this->params()->fromPost('data', array());
// Create a new entity with $data
// Return the properties from the new entity
return array();
}
protected function editRow()
{
$id = $this->params()->fromPost('id');
$data = $this->params()->fromPost('data', array());
// Fetch the entity with id $id
// Update the entity with $data
// Return the properties from the entity
return array();
}
protected function deleteRow()
{
$ids = $this->params()->fromPost('data', array());
// Remove all entities with an id in the array $ids
}
}

Related

Select2 optgroup format using PHP

I've got an ajax call that get dynamic data and places them in select2 as follow :
$.ajax({
type: 'get',
url: '/api/?stuff='+c,
dataType: "json",
success: function (response) {
// If select2 is already defined, we destroy it and rebuild it with the new data
if(typeof $(".select2edit").data('select2') !== 'undefined') {
$(".select2edit").select2('destroy').select2({ data: response, width: '100%', closeOnSelect: false });
} else {
$(".select2edit").select2({ data: response, width: '100%', closeOnSelect: false });
}
}
});
I create the response using PHP and then transform it to JSON before sending it :
$old_emplacement = '';
$results = array();
$i = -1;
while($array_campaign = tep_db_fetch_array($campaign)){
if ($array_campaign['name'] != $old_emplacement) {
$i++;
$results['results'][$i]['text'] = $array_campaign['name'];
$old_emplacement = $array_campaign['name'];
$c = 0;
}
$results['results'][$i]['children'][$c]['id'] = $array_campaign['id'];
$results['results'][$i]['children'][$c]['text'] = $array_campaign['c_name'];
$c++;
}
$results['pagination']["more"] = true;
Thus resulting in the following JSON format :
{
"results": [
{
"text": "Name 1",
"children" : [
{
"id": 1,
"text": "Text 1.1"
},
{
"id": 2,
"text": "Text 1.2"
}
]
},
{
"text": "Name 2",
"children" : [
{
"id": 1,
"text": "Text 2.1"
},
{
"id": 2,
"text": "Text 2.2"
}
]
}
],
"paginate": {
"more": true
}
}
I get a No results found. when select2 initializes and loads. And I have no idea why. It's the correct format as far as the documentation is saying and other questions seem to confirm. Any ideas where could the problem be coming from?
It's also good to note that my select2 is inside a form which is inside a modal, and this is it's html :
<select name="xx[]" id="edit-xx" name='xx' class="form-control select2edit" multiple>
</select>
The problem was with the format generated by my PHP code. I'm posting the result here for anyone trying to generate a select2 optgroup format using PHP and for my own reference :
$old_emplacement = '';
$results = array();
$i = -1;
while($array_campaign = tep_db_fetch_array($campaign)){
if ($array_campaign['name'] != $old_emplacement) {
$i++;
$results[$i]['text'] = $array_campaign['name'];
$old_emplacement = $array_campaign['name'];
$c = 0;
}
$results[$i]['children'][$c]['id'] = $array_campaign['id'];
$results[$i]['children'][$c]['text'] = $array_campaign['c_name'];
if(in_array($array_campaign['id'], $campaigns_array)) {
$results[$i]['children'][$c]['selected'] = true;
}
$c++;
}

Send Data from Cassandra to DataTables (NoSQL)

Hey Guys I have a problem. I`m new to Cassandra and DataTables and my task is to send data from our 'Cassandra-Server' to the Table plug-in 'DataTables'.
I was looking for some examples or tutorials but I never found one for Cassandra-NoSQL.
I tried the following and this Error is always occurring:
PHP:
//setting header to json
header('Content-Type: application/json');
include 'connect.php';
$statement = new Cassandra\SimpleStatement("SELECT * FROM table1");
$result = $session->execute($statement);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//now print the data
print json_encode($data);
JS:
$(document).ready(function () {
'use strict';
var table = $('#main').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "php/server-side.php",
"type": "GET"
},
"columns": [
{ "data": "name" },
{ "data": "type1" },
{ "data": "type2" },
{ "data": "type3" },
{ "data": "land" },
{
"data": "id",
"orderable": false
}
],
"order": [[0, 'asc']]
});
});
Error:
*Uncaught TypeError: Cannot read property 'length' of undefined
jquery.dataTables.min.js: 39*
I think DataTables don't know what to do with the information (json/$data).
In this example https://datatables.net/examples/data_sources/server_side.html
sspclass.php is used but it is written in SQL so no use for me =(
Can somebody help me with this specific problem?

Datatable row grouping

I have a working datatable that is retrieving data from a file :
I want to group row, something like this :
https://datatables.net/examples/advanced_init/row_grouping.html
My goal would to have my datatable to look like this, grouping row by the date (last column), but even looking at the code, I have trouble to make it work. I'd like some help to make that work if you could.
Here is the code of my datatable :
$(document).ready(function() {
$('#datatable').DataTable( {
"ajax": "<?php echo base_url()."assets/files/data/data.txt"; ?>" ,
"columns": [
{ "data": "etat" },
{ "data": "dest" },
{ "data": "message" },
{ "data": "exp" },
{ "data": "date" }
],
"order": [[ 0, "desc" ]],
"responsive": true
} );
} );
You should use drawCallback function.
Try.
$(document).ready(function() {
$('#datatable').DataTable({
"columns": [
{ "data": "etat" },
{ "data": "dest" },
{ "data": "message" },
{ "data": "exp" },
{ "data": "date" },
{ "data": "extra" }
],
"order": [[ 4, "desc" ]],
"responsive": true,
drawCallback: function (settings) {
var api = this.api();
var rows = api.rows({ page: 'current' }).nodes();
var last = null;
api.column(4, { page: 'current' }).data().each(function (group, i) {
if (last !== group) {
$(rows).eq(i).before(
'<tr class="group"><td colspan="8" style="BACKGROUND-COLOR:rgb(237, 208, 0);font-weight:700;color:#006232;">' + 'GRUPO ....' + group + '</td></tr>'
);
last = group;
}
});
}
});
} );
Result: https://jsfiddle.net/cmedina/7kfmyw6x/13/
It seems you get the error when outputting the url by PHP into the Javascript.
Try this instead:
ajax: "<?php echo base_url() . 'assets/files/data/data.txt'; ?>"
Not the single-qoutes in the PHP-code.

How to send a post request to a PHP element

var table = $('#accessRequest').DataTable({
"dom": 'Blfrtip',
"ajax": "Editor-PHP-1.5.1/php/editor-serverside.php",
"columns": [
{ //special column for detail view
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ data: "DT_RowId",
render: function ( data ) {
return data.replace( 'row_', '' );
}
},
{ data: null,
render: function ( data, type, row ) {
// Combine the first and last names into a single table field
return data.first+' '+data.last;
}
},
{ "data": "phone" },
{ "data": "responsibleParty" },
{ "data": "email" },
{ "data": "building" },
{ "data": "typeOfWork" },
{ "data": "startTime" },
{ "data": "endTime" },
{ "data": "description" },
{ "data": "dockNeeded" },
{ "data": "numPeople" },
{ "data": "numTrucks" },
{ "data": "requestPlaced" },
{ "data": "updatedAt" },
{ "data": "approved" },
{ "data": "approvedBy" },
{ "data": "approvedAt" },
{ "data": null }
],
"aoColumnDefs": [
{
"aTargets": [-1],
"mData": null,
"mRender": function (data, type, full) {
return '<button id="ApprovalButton" onclick="$.post(\'extra.php\', \'approve_request\')" action="extra.php" method="post"> Process </button>';
//Send post request
}
}
],
"order": [[1, 'asc']],
select: true,
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
]
});
I have a string of code (above) in which I am creating a table to contain information. On the line that says "//send post request" I'm trying to make it so the button directly above it sends a post request to a separate file called "extra.php", and despite what I've done I haven't been able to that.
I've tried using a submit button in an input form, but that didn't work. I've tried a lot of different things, but I can't seem to get it to work. Any help would be appreciated.
There is already a file (extra.php) that is capable of receiving a post request and acting on it once it has received it. I'm attempting to create a button in HTML on a page, that when clicked posts 'approve_request' to the file "extra.php"
Sorry, I'm new to both coding and this website, there's probably something simple that I'm not doing.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
header('Access-Control-Allow-Origin: *');
$id = intval($_POST['id']);
$con = mysql_connect("RequestAccess.db.10160035.hostedresource.com","RequestAccess","br#6HeCher");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("RequestAccess", $con);
//if action sent is approve set request as apporved
if(isset($_POST['approve_request'])){
$sql = "UPDATE AccessRequests
SET approved='1', approvedAt=current_timestamp
WHERE AccessID='" . $_POST['approve_request']."'";
$results = mysql_query($sql);
}
//else action sent must be for child rows so populate child row
else {
}
This is the section responsible for handling the post request, if that helps.
First of all, some browsers block sending requests with JS so add this on top of your PHP code
header('Access-Control-Allow-Origin: *');
Now you can send a request without problems.
$.post(url ,{
postItem1 : postValue1,
postItem2: postValue2
//You have to define postItem1 and 2 in your PHP code -> $_POST["postItem1"] -> this will return postValue1
}, function(data, status){
//success
}).fail(function() {
//failed
});

Codeigniter Datatables / table add data

i am newbie in web programming and datatables and i am trying to add new data to my tables using fnAddData() but it not work
here is my code
$('#btn_ubahbj').click( function() {
//inisialisasi table upproses
Otableupproses=$('#tableupproses').dataTable( {
'sDom': 't',
"bServerSide": false,
"sServerMethod": "POST",
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "idbom", "value": window.id_bom } );
},
"sAjaxSource": "<?=base_url()?>index.php/master_bj/ambilbomproses",
"sAjaxDataProp": "callback",
"bDestroy": true,
"bAutoWidth": false,
"aoColumns": [
{ "sTitle": "ID Proses", "mDataProp": "id_proses_produksi"},
{ "sTitle": "Nama Proses", "mDataProp": "nama"},
{ "sTitle": "Lama Proses", "mDataProp": "waktu"},
{ "sTitle": "Jumlah Mesin", "mDataProp": "jumlah_mesin"},
]
} );
} );
$('#btnuptambahproses').click(
Otableupproses.fnAddData( [$('#prosesupbj').val(),$("#prosesupbj option:selected").text(),$('#txtuplamaproses').val(),$('#txtupjmlmesin').val()]
);
});
my controller name master_bj
function ambilbomproses()
{
$idbom= $this->input->post('idbom');
$res['dataproses']=$this->bom_punya_proses_model->getbomproses($idbom);
echo json_encode(array("callback" => $res['dataproses']));
}
how can i dinamically add new row ?
i use fnAddData() it not work because i get data from json
please help
my model class name bom_punya_proses_model
function getbomproses($idbom)
{
$sql= "SELECT proses_produksi_punya_bom.id_proses_produksi, proses_produksi.nama, proses_produksi_punya_bom.waktu, proses_produksi_punya_bom.jumlah_mesin
FROM proses_produksi_punya_bom
INNER JOIN proses_produksi ON proses_produksi_punya_bom.id_proses_produksi = proses_produksi.id_proses_produksi
WHERE proses_produksi_punya_bom.id_bom = '".$idbom."'";
$result= $this->db->query($sql);
if($result->num_rows() > 0){
return $result->result_array();
}else
return false;
}
no problem with my query and controller , because the json has been performed correctly , but the problem is when i try to add new row data to table ,
Your model does not appear to be using the active records portion of the codeigniter framework at all.
Check the tutorial on the CI website and have a look at the active record help page at :
http://ellislab.com/codeigniter/user-guide/database/active_record.html

Categories