Using aoData.push with POST
Using aoData.push with POST
I looked everywhere and couldn't find an answer so I thought I'd ask!
I'm trying to post the value extradata to the workouts.php file using the aoData.push. I can receive it in workouts.php when I use GET and load the page for the first time but anytime after that its not being passed through.
Is there something I'm just forgetting to do or can you only receive data that has been "pushed" using GET? The rest of the data in the row is accessible all the time in workouts.php regardless. Any more info on this would be great!
[code]
// DataTables init
$('#example').dataTable( {
type: \"POST\",
\"sAjaxSource\": \"php/workouts.php\",
\"fnServerParams\": function ( aoData ) {
aoData.push( { \"name\": \"extradata\", \"value\": \"14\" } );
},
\"aoColumns\": [
{ \"mDataProp\": \"name\", \"sClass\": \"center\" },
{ \"mDataProp\": \"date\", \"sClass\": \"center\" },
{ \"mDataProp\": \"type\", \"sClass\": \"center\" },
{ \"mDataProp\": \"target\", \"sClass\": \"center\" },
{ \"mDataProp\": \"time\", \"sClass\": \"center\" },
{ \"mDataProp\": \"distance\", \"sClass\": \"center\" },
{ \"mDataProp\": \"speed\", \"sClass\": \"center\" },
{ \"mDataProp\": \"notes\", \"sClass\": \"center\" },
{
\"mDataProp\": null,
\"sClass\": \"center\",
\"sDefaultContent\": 'Edit',
\"bSortable\": false,
\"bSearchable\": false
},
{
\"mDataProp\": null,
\"sClass\": \"center\",
\"sDefaultContent\": 'Delete',
\"bSortable\": false,
\"bSearchable\": false
}
],
\"fnInitComplete\": function () {
keys.fnSetPosition( 0, 0 );
}
[/code]
I'm trying to post the value extradata to the workouts.php file using the aoData.push. I can receive it in workouts.php when I use GET and load the page for the first time but anytime after that its not being passed through.
Is there something I'm just forgetting to do or can you only receive data that has been "pushed" using GET? The rest of the data in the row is accessible all the time in workouts.php regardless. Any more info on this would be great!
[code]
// DataTables init
$('#example').dataTable( {
type: \"POST\",
\"sAjaxSource\": \"php/workouts.php\",
\"fnServerParams\": function ( aoData ) {
aoData.push( { \"name\": \"extradata\", \"value\": \"14\" } );
},
\"aoColumns\": [
{ \"mDataProp\": \"name\", \"sClass\": \"center\" },
{ \"mDataProp\": \"date\", \"sClass\": \"center\" },
{ \"mDataProp\": \"type\", \"sClass\": \"center\" },
{ \"mDataProp\": \"target\", \"sClass\": \"center\" },
{ \"mDataProp\": \"time\", \"sClass\": \"center\" },
{ \"mDataProp\": \"distance\", \"sClass\": \"center\" },
{ \"mDataProp\": \"speed\", \"sClass\": \"center\" },
{ \"mDataProp\": \"notes\", \"sClass\": \"center\" },
{
\"mDataProp\": null,
\"sClass\": \"center\",
\"sDefaultContent\": 'Edit',
\"bSortable\": false,
\"bSearchable\": false
},
{
\"mDataProp\": null,
\"sClass\": \"center\",
\"sDefaultContent\": 'Delete',
\"bSortable\": false,
\"bSearchable\": false
}
],
\"fnInitComplete\": function () {
keys.fnSetPosition( 0, 0 );
}
[/code]
This discussion has been closed.
Replies
@mars - what is "retrieveJsonData" and do you know zippy1991 is using it? Its certainly not a PHP function I'm aware of. Also I'm not sure I understand its relevance?
Allan
@zippy1991 - sorry for the trouble i made for you. here is the code what i use, maybe it could give you some info:
var oTable = $('#data_table').dataTable({
"bScrollCollapse": true,
"bAutoWidth": true,
"sScrollX": "100%",
"iDisplayLength": 25,
"sDom": 'Rti',
"bServerSide": true,
"sAjaxSource": "/monitor/DataTable/",
"bDestroy":true,
"fnServerData": retrieveJsonData
});
function retrieveJsonData (sSource, aoData, fnCallback) {
var para = {
aoData : JSON.stringify(aoData),
"para1": "para1"
};
$.ajax({
"type" : "post",
"contentType" : "application/json",
"url" : sSource,
"dataType" : "json",
"data" : para,
"success" : function(resp) {
fnCallback(resp);
}
});
}
The code I pasted above gets sent to the code below. The page loads fine (and the extradata is being passed through) but any updates or creates don't work as they need extradata value to be passed in again, which is giving rise to the error " Undefined index: extradata".
So what I was wondering was why isn't the extradata being passed in any time I try and do an update or create but the rest of the values are being passed in? Sorry in advance. My coding isn't the best!
[code]
include( "include/db.php" );
$extradata = $_POST['extradata'];
$editor = new DTEditor(
$db, // DB resource
'workouts', // DB table
'id', // Primary key
'row_', // ID prefix to add to the TR rows (makes it valid and unique)
array( // Fields
new DTField( array(
"name" => "name",
"dbField" => "name",
"validator" => "DTValidate::required"
) ),
new DTField( array(
"name" => "date",
"dbField" => "date",
"validator" => "DTValidate::required"
) ),
new DTField( array(
"name" => "type",
"dbField" => "type"
) ),
new DTField( array(
"name" => "target",
"dbField" => "target"
) ),
new DTField( array(
"name" => "time",
"dbField" => "time"
) ),
new DTField( array(
"name" => "distance",
"dbField" => "distance"
) ),
new DTField( array(
"name" => "speed",
"dbField" => "speed"
) ),
new DTField( array(
"name" => "notes",
"dbField" => "notes",
"validator" => "DTValidate::required"
) )
),
$extradata
);
// The "process" method will handle data get, create, edit and delete
// requests from the client
echo json_encode( $editor->process($_POST) );
[/code]
Allan
The rows currently in the database show up but I can't edit/create.
This is the doc comment for the old DTEditor class:
[code]
/**
* DataTables Editor class - This class provides everything that is needed for a
* full CRUD table using DataTables and Editor, on a single database table (note that
* currently it does not support linked tables).
* @param resource $db The MySQL DB handle to use
* @param string $table The table name in the database to use for the CRUD table
* @param string $primaryKey Primary key column name in the table
* @param string $primaryKeyPrefix Prefix to add to the primary key to make it a
* valid DOM ID (i.e. must start with a letter), and also useful for cases where
* multiple Editor tables are used on a single page to ensure uniqueness of row IDs
* @param array $fields An array of DTField objects defining the filed to get and
* set, including formatting, validation etc, for the table / form.
*/
[/code]
If you want to have an extra field called `extradata` , can you not just add it to the field list?
Allan
This is some of the modified DTEditormysql.pdo.class.php
[code]
class DTEditor {
private $_db = null;
private $_primaryKey = "";
private $_primaryKeyPrefix = "";
private $_table = "";
private $_fields = array();
private $_formData;
private $_extradata = "";
private $_out = array(
"id" => -1,
"test" => "",
"error" => "",
"fieldErrors" => array(),
"data" => array()
);
function __construct( $db, $table, $primaryKey, $primaryKeyPrefix, $fields, $extradata )
{
$this->_db = $db;
$this->_table = $table;
$this->_primaryKey = $primaryKey;
$this->_primaryKeyPrefix = $primaryKeyPrefix;
$this->_fields = $fields;
$this->_extradata = $extradata;
}
/**
* Process a request from DataTables to get data, or from Editor to set it
* @param array $data $_POST or $_GET as required by what is sent by Editor
* @return array Array that should be JSON encoded and sent back to Editor
*/
public function process ( $data )
{
$this->_formData = isset($data['data']) ? $data['data'] : null;
if ( !isset($data['action']) ) {
/* Get data */
$this->_get();
}
else if ( $data['action'] == "remove" ) {
/* Remove rows */
$this->_remove();
}
else {
/* Create or edit row */
// Individual field validation
for ( $i=0 ; $i_fields) ; $i++ ) {
$field = $this->_fields[$i];
$validation = $field->validate( $this->_formData );
if ( $validation !== true ) {
$this->_out['fieldErrors'][] = array(
"name" => $field->name,
"status" => $validation
);
}
}
// Global validation - if you want global validation - do it here
$this->_out['error'] = "";
if ( count($this->_out['fieldErrors']) === 0 ) {
if ( $data['action'] == "create" ) {
$this->_insert();
}
else {
$this->_update( $data['id'] );
}
}
}
return $this->_out;
}
/**
* Get an array of objects from the database to be given to DataTables as a
* result of an sAjaxSource request, such that DataTables can display the information
* from the DB in the table.
* @private
*/
private function _get()
{
$stmt = $this->_db->prepare( "
SELECT ".$this->_fields('get', '`%s`', true)."
FROM {$this->_table}
WHERE clubid = {$this->_extradata}
" );
if ( ! $this->_execute( $stmt ) ) {
return;
}
$this->_out['aaData'] = array();
while ( $row=$stmt->fetch() ) {
$inner = array();
$inner['DT_RowId'] = $this->_primaryKeyPrefix . $row[ $this->_primaryKey ];
for ( $i=0 ; $i_fields) ; $i++ ) {
$field = $this->_fields[$i];
if ( $field->apply('get') ) {
$inner[ $field->name ] = $field->val('get', $row);
}
}
$this->_out['aaData'][] = $inner;
}
}
/**
* Insert a new row in the database
* @private
*/
private function _insert()
{
$stmt = $this->_db->prepare( "
INSERT INTO {$this->_table}
(".$this->_fields('set', '`%s`').",`clubid`".")
VALUES
(".$this->_fields('set', ':%s').",'{$this->_extradata}'".")
" );
$this->_bindValues( $stmt, $this->_formData );
if ( ! $this->_execute( $stmt ) ) {
return;
}
$id = $this->_db->lastInsertId();
// Dynamic get for fields which might have been updated on the DB
$this->_dynamicGet( $id );
$this->_out['id'] = $this->_primaryKeyPrefix . $id;
}
[/code]
Thanks again for the help! And sorry for being a nuisance!
On edit, the error is:
> Notice: Undefined index: extradata in [...]/workouts.php on line 9
And right enough, `extradata` isn't being sent. From what you say, I guess you expect it to be? For that you want to use the `onSubmit` event of Editor. Editor does not use the fnServerData option of DataTables, it makes its own Ajax call, so you need to add `extradata` there ( http://editor.datatables.net/options/#onPreSubmit ).
Allan
[code]
$(document).ready(function() {
var editor = new $.fn.dataTable.Editor( {
\"ajaxUrl\": \"php/workouts.php\",
\"domTable\": \"#example\",
\"events\": {
\"onPreSubmit\": function ( o ) {
o.data.extradata = '14';
}
}
[/code]
Allan
[code]
if ( isset($_POST['extradata']) ){
$extradata = $_POST['extradata'];
}
else{
$extradata = $data['data']['type'];
}
[/code]
Thanks again for all the help and keep up the amazing work!!