Using aoData.push with POST

Using aoData.push with POST

zippy1991zippy1991 Posts: 6Questions: 0Answers: 0
edited April 2013 in General
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]

Replies

  • marsmars Posts: 29Questions: 2Answers: 0
    i suggest you use "retrieveJsonData" to post jsondata, i am using it now, and it works fine. in addition, i think JsonData is more lightweight and fast
  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin
    @zippy1991 - You say that your parameter is being passed through on load, "but anytime after that its not being passed through" - I don't quite understand this part - what are you doing that you would expect the data to be sent to the server again? You are Ajax loading client-side processing data, so DataTables will only call the server once (unless you use a plug-in such as fnReloadAjax?).

    @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
  • marsmars Posts: 29Questions: 2Answers: 0
    @allan - sorry i write the wrong words, what i want to say is the property "fnServerData".

    @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);
    }
    });
    }
  • zippy1991zippy1991 Posts: 6Questions: 0Answers: 0
    edited May 2013
    I thought I had it working but apparently not! The issue I'm having is (as I wasn't clear enough above) when trying to use the editor plugin to update or create a new row.

    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]
  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin
    Can you link to a test page showing the issue please?

    Allan
  • zippy1991zippy1991 Posts: 6Questions: 0Answers: 0
    http://rowinginfo.jkearney.ie/workouts.php You'll have to login with testclub as the club and password as the password.

    The rows currently in the database show up but I can't edit/create.
  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin
    The old Editor PHP libraries (which it looks like you are using) don't have a 6th initialisation parameter option (where you've got `$extradata` ). I'm not entirely sure what the intention with it is?

    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
  • zippy1991zippy1991 Posts: 6Questions: 0Answers: 0
    I wanted to pass in a encrypted id so the data would be user specific. I had modified the DTEditormysql.pdo.class.php file so everything was working when I had hard coded the value into the code sample above. If the worst come to the worst I can always just make another field and just hide it with via css but if there was any way other simple fix it would be great.

    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!
  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin
    Okay, I think I'm getting the picture now.

    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
  • zippy1991zippy1991 Posts: 6Questions: 0Answers: 0
    That makes a lot more sense to me now! One last question! To pass in the extradata value before I submit it how would I go about doing it? The code I pasted below I wrong but I couldn't find any examples anywhere and my javascript is terrible.

    [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]
  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin
    That looks like it should work for me (minus the escaped strings of course)! Does it not add the extra data parameter to what it sent to the server? Are you able to link me to the page?

    Allan
  • zippy1991zippy1991 Posts: 6Questions: 0Answers: 0
    Got it working!! I needed to add an extra line to get the table to appear in the first place.

    [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!!
This discussion has been closed.