How to send $_POST[var] to ssp by ajax

How to send $_POST[var] to ssp by ajax

mdesignmdesign Posts: 72Questions: 17Answers: 0

i have an ajax issue and hope somebody can help.
my POST Vars does not appear within the ssp file. whats wrong ?

// 1) Datatable Editor
var thisDataTable = $('table.editorTable').DataTable({
ajax:  { 
  url:  'my-ssp.php', 
  type: 'POST',
  data: {
    'pdoField' : 'webx_idn',
    'webx_idn' : 'domain.com',
  }
},


// 2) my-ssp.php
// this works!
->where('webx_idn', 'domain.com')

// doesn't work !!! a system error has occurred 
// Chrome XHR Log "Undefined index: pdoField"
->where($_POST['pdoField'], $_POST['webx_idn'])

Answers

  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin

    That looks like it should work! Perhaps you could try:

    data: function (d) {
      d.pdoField = 'webx_idn';
      d.webx_idn' = 'domain.com';
    }
    

    i.e. using it as a function instead. If that doesn't solve it, could you give me a link to a test case showing the issue?

    One thing - you must sanitise the pdoField that is being submitted from the client-side. Make sure it is one of the column names you are expecting, otherwise you leave yourself open to an SQL injection attack!

    Allan

  • mdesignmdesign Posts: 72Questions: 17Answers: 0

    Alan. No its doesn't work either. How can i give you test case ?

  • mdesignmdesign Posts: 72Questions: 17Answers: 0

    thx tangerine. how can i show a testcase where an -ssp.php file ist included.
    like:
    ajax: 'path-to-ssp.php'

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    A link to the page would be helpful, so we could confirm the values are being passed. Or if you could post that here, that would also be helpful,

    Colin

  • mdesignmdesign Posts: 72Questions: 17Answers: 0

    thx colin for your help. would be so great, if we can solve this problem. this is an shortened example:

    the ssp-File

    header('Access-Control-Allow-Origin: *'); // allow cross domains
    
    // Database => dtEditor/xxx/lib/config.php
    $cnf['database']['pdoName'] = 'db78286_5';
    
    // DT Editor PHP library
    include_once('-dtEditor/1.9.6/lib/DataTables.php');
    
    // Used Vars in ssp Files
    $date_sql = 'Y-m-d H:i:s';  // 2019-12-31 23:59:00  siehe php.net/manual/de/function.date
    $datetime = 'd/m/Y - H:i';  // 31/12/2019 - 12:12   editor field => format:'DD/MM/YYYY - HH:mm'
    
    use
        DataTables\Editor,
        DataTables\Editor\Field,
        DataTables\Editor\Format,
        DataTables\Editor\Mjoin,
        DataTables\Editor\Options,
        DataTables\Editor\Upload,
        DataTables\Editor\Validate,
        DataTables\Editor\ValidateOptions;
    
    $db->sql('set names utf8');
    $editor = Editor::inst(
      $db, 'alle_zzzz', 
           'alle_zzzz.zzzz_idn' /* Primary Key */
      )
        ->fields(
        Field::inst('alle_zzzz.webx_idn'),
        Field::inst('alle_zzzz.zzzz_idn'),
        Field::inst('alle_zzzz.zzzz_sta'),
    
        /* letztes Field Update mySql Timestamp */
        Field::inst('alle_zzzz.zzzz_upd')
          ->validator(Validate::dateFormat($datetime))
          ->getFormatter(Format::datetime( $date_sql, $datetime))
          ->setValue(date($date_sql, time())) // kein ',' am Ende
        );
    
    $editor
      ->where($_POST['pdoField'], $_POST['webx_idn']) /* does not work => undefined index: pdoField */
    //->where('alle_zzzz.webx_idn', 'domain.com')     /* does work */
      ->debug(true)
        ->process($_POST)
        ->json();
    

    the table File

    <table border="1" class="table | table-default | table-dashboard | editorTable | .table-dbug | .table-indexRow | .table-indexCol">
      <thead valign="top">
        <tr align="left">
          <th class="th-idex | noColVis" data-orderable="false"><a data-smooth-scroll href="#endOfTable" title="zum Tabellenende scrollen"><i class="fas | fa-angle-double-down"></i></a></th>
          <th class="th-idnx"><br><smaller>idn</smaller></th>
          <th class="th-icon" data-orderable="false"><abbr>Löschen</abbr></th>
          <th class="th-icon" data-orderable="false"><abbr>Bearbeiten</abbr></th>
          <th><b>Upload</b><br><smaller>Beta</smaller></th>
          <th><b>date</b><br><smaller>edit | zzzz_dup (keine anzeige ?)</smaller></th>
          <th><b>datetime</b><br><smaller>edit | zzzz_dto</smaller></th>
          <th><b>Update</b><br><smaller>no edit</smaller></th>
          <th><b>Site</b></th>
        </tr>
        </thead>
    
      <tbody valign="top"></tbody>
    </table>
    <script>
    $(document).ready(function($) {
      /* -------------------------------------------------------------------------- *
        .dataTable                                                   [ thisEditor ]
         defaults => datatables-editor.js
       * -------------------------------------------------------------------------- */
      editor = new $.fn.dataTable.Editor({
        ajax:  '<?= $_SESSION[$siteDOMAINX]['siteRELBASE']; ?>/set-golf20/-admin/editor-alle_zzzz-ssp.php',
        table: 'table.editorTable',
      //template: '.customForm',  /* https://editor.datatables.net/manual/templates */
        fields: [ 
          // Site
          { name:  'alle_zzzz.webx_idn', 
            label: 'Site',
            type:  'select',
            options: [
              { label: '-', value: '' },
            <? foreach($pdoAdmiWeb as $key => $val) { /* Dieser SELECT siehe -conf-admin.php */ ?>
              { label: '<?= $val['webx_idn']; ?>', 
                value: '<?= $val['webx_idn']; ?>' },
            <? } ?>
            ]
          },
          
          // Datum (date)
          { name:  'alle_zzzz.zzzz_dup', 
            label: 'Datum',
            type:  'datetime',
            format: 'DD/MM/YYYY', /* Formate siehe zzzz-ssp Template (doesn't show up within the table */
            opts:  { showWeekNumber: true },
          },
          
          // Datum (datetime)
          { name:  'alle_zzzz.zzzz_dto', 
            label: 'Datum',
            type:  'datetime',
            format:'DD/MM/YYYY - HH:mm', /* Formate siehe zzzz-ssp Template */
            opts:  { showWeekNumber: true },
          },
      
          // Upload (beta)
          { name:  'alle_zzzz.zzzz_upl', // 'users_images.imageId',
            label: 'Upload:',
            type:  'upload',
            display: function (id) {
                return '<img src="' + editor.file('images',id).webPath + '"/>';
            },
            noImageText: 'No image',
          },
        ],
      }); /* fn.dataTable.Editor */
    
    
    
    /* -------------------------------------------------------------------------- *
      .dataTable                                                   [ thisTables ]
       defaults => app-datatables-tables-defaults.js
     * -------------------------------------------------------------------------- */
      var thisDataTable = $('table.editorTable').DataTable({
        ajax:  { 
          url:  '<?= $_SESSION[$siteDOMAINX]['siteRELBASE']; ?>/set-golf20/-admin/editor-alle_zzzz-ssp.php', 
          type: 'POST',
          data: {
            pdoField : 'alle_zzzz.webx_idn',
            webx_idn : '<?= $_SESSION['dashboard']['web']; ?>',
          }
        },
        order:       [[1, 'desc' ]], /* default (idn) wenn nicht stateSave */
        pageLength:  5,
        stateSave:   true,
        colReorder:  true,  
        columns: [
          // Spalten (1) index / (2) idn / (3) trash / (4) edit
          { className: 'th-idex', data: null, defaultContent: '' /* indexRow content by CSS */ },
          { className: 'th-idnx', data: 'alle_zzzz.zzzz_idn' },
          { className: 'th-icon', data: null, defaultContent: '<a class="editor_remove" title="Eintrag entfernen"><i class="far | fa-trash-alt"></i></a>' },
          { className: 'th-icon', data: null, defaultContent: '<a class="editor_edit" title="Eintrag bearbeiten (Lightbox)"><i class="fas | fa-edit"></i></a>' },  
      
          // Upload
          { data: 'image',
            className: '-text-center', 
            render: function (file_id) {
              return file_id;
            //return file_id ? '<img src="'+editor.file('files', file_id ).web_path+'"/>' : null;
            },
            defaultContent: '<i class="fas | fa-image"></i>',
          },
      
          // Datum (date)
          { data: 'alle_zzzz.zzzz_dup', 
            className: '-text-right',
          },
      
          // Datum (datetime)
          { data: 'alle_zzzz.zzzz_dto', 
            className: '-text-right',
          },
      
          // Datum Update
          { data: null,
            className: 'th-date',
            render: function (data, type, row) {
                                                                 var output = data.alle_zzzz.zzzz_upd.replace(' - ', '<br>'); /* Zeilenumbruch vor Uhrzeit */
                      if(data.alle_zzzz.zzzz_upd.includes('0001')) { output = ''; } /* kein Datum mysql(000-00-00 00:00:00) kommt von ssp als '30/11/-0001 - 00:00' zurück */
                      return output;
            }
          },
      
          // webx_idn
          { data: 'alle_zzzz.webx_idn' },
        ],
      
      
        /* ------------------------------------------------------ *
         * Buttons                (hier thisDataTable definieren)
         * ------------------------------------------------------ */
        buttons: [
          // Button Hilfe - öffnet Modal
          { text:      '<i class="fas | fa-info-circle"></i>', 
            titleAttr: 'Hilfe',
            action:     function () { $('#reveal-dttipps').foundation('open'); } 
          },
        
          // Button Table - state.clear()
          { text:      '<i class="fas | fa-recycle"></i>', 
            titleAttr: 'Tabelle Reset',
            action:     function () { thisDataTable.state.clear(); window.location.reload(); alert('Recycle Tabelle. Alle Tabellen Filter zurücksetzen.'); } 
          },
        
          // Button Table - 'ColVis' - datatables.net/reference/button/colvis
          { extend:    'colvis',
            text:      '<i class="fas | fa-columns"></i>',
            titleAttr: 'Spalten ein/ausblenden',
            className: '-subs-text-left', /* eigene Class */
            columns:   ':not(.noColVis)', /* siehe th class */
            background: false,
            autoClose:  false,
          },
        
          // Button Table - 'Print'
          { extend:    'print',  
            text:      '<i class="fas | fa-print"></i>', 
            titleAttr: 'Drucken', 
            autoPrint:  true 
          },
        
          // Button Table - 'Export' Collection - datatables.net/extensions/buttons/built-in
            { extend:    'collection',
            text:      '<i class="fas | fa-download"></i>',
            titleAttr: 'Download',
            className: '-subs-text-left', /* eigene Class */
            background: false,
            autoClose:  true,
            buttons: [
              { extend: 'copyHtml5',  text: '<i class="far | fa-fw | fa-files"></i>      Auswahl <b>kopieren </b>' },
              { extend: 'csvHtml5',   text: '<i class="far | fa-fw | fa-file-alt"></i>   Auswahl <b>Export CSV</b>' },
            ],
          },
        
            // Button Editor - 'Edit' / 'Delete' / 'Neu' (float: right)
          { extend: 'remove', text: '<i class="far | fa-trash-alt"></i><abbr>Löschen</abbr>', titleAttr: 'Löschen',        className: '-float-right',            editor: editor },
          { extend: 'edit',   text: '<i class="fas | fa-edit"></i><abbr>Bearbeiten</abbr>',   titleAttr: 'Bearbeiten',     className: '-float-right',            editor: editor },
          { extend: 'create', text: '<i class="fas | fa-plus-square"></i><abbr>Neu</abbr>',   titleAttr: 'Neu hinzufügen', className: '-float-right -text-bold', editor: editor },
        ], /* buttons */
      
      }); // thisDataTable
    }); // $(document).ready  
    </script>
    
  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin

    Here is a little example: http://live.datatables.net/kedemidu/1/edit . Our post.php script doesn't use those parameters, but I can see them being sent in the network inspector:

    Does it not work when you first load the data? Or does it work then and not when you are performing editing actions? I'm guessing the latter. Your Editor code isn't sending the extra POST parameters. Try:

    ajax: {
      url: '<?= $_SESSION[$siteDOMAINX]['siteRELBASE']; ?>/set-golf20/-admin/editor-alle_zzzz-ssp.php',
      data: function (d) {
        d.pdoField = 'alle_zzzz.webx_idn';
        d.webx_idn' = '<?= $_SESSION['dashboard']['web']; ?>';
      }
    }
    

    in your Editor initialisation.

    Allan

  • mdesignmdesign Posts: 72Questions: 17Answers: 0
    edited December 2020

    @allan. as you mentioned: the error occurs when editing something. with chrome inspaector i can see XHR (in the ssp file):

    <br />
    <b>Notice</b>:  Undefined index: pdoField in <b>/kunden/78286_4020/webseiten/set-pepples/set-golf20/-admin/editor-alle_zzzz-ssp.php</b> on line <b>52</b><br />
    <br />
    <b>Notice</b>:  Undefined index: webx_idn in <b>/kunden/78286_4020/webseiten/set-pepples/set-golf20/-admin/editor-alle_zzzz-ssp.php</b> on line <b>52</b><br />
    <br />
    <b>Fatal error</b>:  Uncaught Error: Call to a member function debug() on array in /kunden/78286_4020/webseiten/set-pepples/set-golf20/-admin/editor-alle_zzzz-ssp.php:54
    Stack trace:
    #0 {main}
      thrown in <b>/kunden/78286_4020/webseiten/set-pepples/set-golf20/-admin/editor-alle_zzzz-ssp.php</b> on line <b>54</b><br />
    
  • mdesignmdesign Posts: 72Questions: 17Answers: 0

    it so frustrating. i don't get it and i spend tons of hours for this now. maybe this tell you something.

    when i print the POST in the ssp file, i can see the value in the chrome inspector, but get the error by datatable Editor.

    ssp.php

    print $_POST['webx_idn']; /* print the correct value */
    $editor
      ->where('alle_zzzz.webx_idn', $_POST['webx_idn']) /* => undefined index: webx_idn */
    
  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin

    I'm presuming you've added the code I suggested above to your Javascript Editor initialisation?

    print $_POST['webx_idn']; /* print the correct value */
    $editor
      ->where('alle_zzzz.webx_idn', $_POST['webx_idn']) /* => undefined index: webx_idn */
    

    I can't understand that. Can you show me the full, unabridged file please?

    Allan

  • mdesignmdesign Posts: 72Questions: 17Answers: 0

    allan. first of all - thx a lot for your patience and a late happy x-mas. maybe my english is confusing you.

    here is the table:
    http://live.datatables.net/suquzuri/1/edit

    and the ssp-file

    /* -------------------------------------------------------------------------- *
       DataTables Editor PHP library
     * -------------------------------------------------------------------------- */
    include_once('-conf-editor.php');
    use
        DataTables\Editor,
        DataTables\Editor\Field,
        DataTables\Editor\Format,
        DataTables\Editor\Mjoin,
        DataTables\Editor\Options,
        DataTables\Editor\Upload,
        DataTables\Editor\Validate,
        DataTables\Editor\ValidateOptions;
    
    $db->sql('set names utf8');
    $editor = Editor::inst(
      $db, 'alle_zzzz', 
           'alle_zzzz.zzzz_idn' /* Primary Key */
      )
        ->fields(
        Field::inst('alle_zzzz.webx_idn'),
        Field::inst('alle_zzzz.zzzz_idn'),
        Field::inst('alle_zzzz.zzzz_sta'),
        Field::inst('alle_zzzz.zzzz_tit'),
        Field::inst('alle_zzzz.zzzz_txt'),
        Field::inst('alle_zzzz.zzzz_dto')
          ->validator(Validate::dateFormat($datetime))
          ->getFormatter(Format::datetime( $date_sql, $datetime))
        //->setFormatter(Format::datetime( $datetime, $date_sql)), // works at UPDATE, not by NEW INSERT
    
          /* (!) works at NEW INSERT, not by UPDATE */
          ->setFormatter( function ($val, $data) {
            return $val ?
              Format::datetime( $datetime, $date_sql)($val, $data)
              : date('c'); // take today's date
          }),      
    
        /* (todo) Upload (siehe editor/example/advanced/upload.html */
    
        /* letztes Field Update mySql Timestamp */
        Field::inst('alle_zzzz.zzzz_upd')
          ->validator(Validate::dateFormat($datetime))
          ->getFormatter(Format::datetime( $date_sql, $datetime))
          ->setValue(date($date_sql, time())) // kein ',' am Ende
        );
    
    // superadmin (kein where)
    if($_SESSION['dashboard']['web'] !== '%') $editor->where('alle_zzzz.webx_idn', $_SESSION['dashboard']['web']);
    
    $editor
    //->where('alle_zzzz.webx_idn', $_POST['webx_idn']) /* does not work => undefined index: pdoField */
    //->where('alle_zzzz.webx_idn', 'domain.com')     /* does work */
      ->debug(true)
        ->process($_POST)
        ->json();
    
  • allanallan Posts: 63,516Questions: 1Answers: 10,472 Site admin

    See my reply to your post on this topic here: https://datatables.net/forums/discussion/65171/if-empty-take-todays-date#latest .

    Allan

This discussion has been closed.