Undefined index error on AJAX call on Datatable Editor when I use upload file feature

Undefined index error on AJAX call on Datatable Editor when I use upload file feature

aneto2400aneto2400 Posts: 58Questions: 8Answers: 1

Hi Allan,
i´ve used send data function previously on AJAX call (below on code) without problems on Datatable Editor, but now I´m using upload file feature on v.1.5.4. appear an error:
"Notice: Undefined index: site in /home/tripntry/www/x.samples/datateditor154/examples/php/upload.php on line 12"

If I remove the function - call to ajax without data values - it works , but I need pass the data value "site". Same error on v.1.5.1. Also I´ve used other way to send data , but same error (sintax in code) .You can to see live example on : http://tripntry.com/x.samples/datateditor154/examples/advanced/upload.v1.html

Any idea?. Thank you in advance!!. Eduardo

 function id_establecimiento(results){
 var id_estblecmto = localStorage.getItem('establecimiento');
return id_estblecmto
 };

var editor; // use a global for the submit and return data rendering in the examples

$(document).ready(function() {
editor = new $.fn.dataTable.Editor( {
    //ajax: "../php/upload.php",
     ajax: {
        url:"../php/upload.php",
        type: "POST",
        //data: {site :  '342800010'},  //same index error
        data: function ( d )    {
            d.site =  id_establecimiento(); //get id (site) after login 
                                }   
            },  

    table: "#example",
    fields: [ 
                    {
                        label: "Nombre (establecimiento):",
                        name: "nom_estbl",
                        status: "This field is required"

                    },
                    {
                        label: "Telefono:",
                        name: "telefono",
                        status: "This field is required"

                    },
                    {
                        label: "E-mail (establecimiento):",
                        name: "email_estbl",
                        status: "This field is required"
                    },

                    {
                        label: "Nº de Plazas:",
                        name: "num_plaz",
                        status: "This field is required"

                    },
                    {
                        label: "Precio medio:",
                        name: "prec_med"
                    },
                    {
                        label: "Site (ID):",
                        name: "site",
                        type: "readonly",
                        def: id_establecimiento,
                    },
                    {
                        label: "Image:",
                        name: "image",
                        type: "upload",
                        display: function ( file_id ) {
                            return '<img src="'+table.file( 'files', file_id ).web_path+'"/>';
                            },
                        clearText: "Clear",
                        noImageText: 'No image'
                    }   
          ]
} );

var table = $('#example').DataTable( {
    dom: "Bfrtip",
    //ajax: "../php/upload.php",
     ajax: {
        url:"../php/upload.php",
        type: "POST",
        //data: {site :  '342800010'},  //same index error
        data: function ( d )    {
            d.site =  id_establecimiento(); //get id (site) after login 
                                }   
            },

    columns: [
                    { data: "nom_estbl" },
                    { data: "telefono" },
                    { data: "email_estbl" },
                    { data: "num_plaz" },
                    { data: "prec_med" },
                    {
                        data: "image",
                        render: function ( file_id ) {
                            return file_id ?
                                '<img src="'+table.file( 'files', file_id ).web_path+'"/>' :
                                null;
                        },
                        defaultContent: "No image",
                        title: "Image"
                    }
            ],
    select: true,
    buttons: [
        { extend: "create", editor: editor },
        { extend: "edit",   editor: editor },
        { extend: "remove", editor: editor }
    ]
   } );
  } );

Server side (upload.php)

 // DataTables PHP library
include( "../../php/DataTables.php" );

//$site="342800010"; 
$site=$_POST['site'];  //here point the error!!!

// Alias Editor classes so they are easy to use
use
DataTables\Editor,
DataTables\Editor\Field,
DataTables\Editor\Format,
DataTables\Editor\Join,
DataTables\Editor\Upload,
DataTables\Editor\Validate;

 // Build our Editor instance and process the data coming from _POST
 Editor::inst( $db, 'r_clientes' )
->fields(
    Field::inst( 'nom_estbl' ),
    Field::inst( 'telefono' ),
    Field::inst( 'email_estbl' ),
    Field::inst( 'num_plaz' ),
    Field::inst( 'prec_med' ),
    Field::inst( 'site' ),
    Field::inst( 'image' )
        ->setFormatter( 'Format::ifEmpty', null )
        ->upload( Upload::inst( $_SERVER['DOCUMENT_ROOT'].'/upload/__ID__.__EXTN__' )
            ->db( 'files', 'id', array(
                //'site'            =>$site,
                'filename'    => Upload::DB_FILE_NAME,
                'filesize'    => Upload::DB_FILE_SIZE,
                'web_path'    => Upload::DB_WEB_PATH,
                'system_path' => Upload::DB_SYSTEM_PATH
            ) )
            ->validator( function ( $file ) {
                return$file['size'] >= 3500000  ?
                    "Files must be smaller than 3500K o 3,5 Mb" :
                    null;
            } )
                            //delete orphan files. INICIO
            ->dbClean( function ( $data ) {
                            // Remove the files from the file system
                            for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) {
                                unlink( $data[$i]['system_path'] );
                            }

                            // Have Editor remove the rows from the database
                            return true;
                        } )
            //delete orphan files. FIN

            ->allowedExtensions( array( 'png', 'jpg', 'gif' ), "Please upload an image" )
        )
)

->where( 'site', $site)
->process( $_POST )
->json();

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    You would need to use the ajaxData option of the upload field type to add the site parameter to that Ajax request as well. You will need to update to Editor 1.5.4 to be able to use that property as it was introduced in that version.

    Allan

  • aneto2400aneto2400 Posts: 58Questions: 8Answers: 1
    edited February 2016

    My apologies, I´ve tried to resolve but nothing. Can write an example to see how to pass "site" value with ajaxData? Thank you!

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    edited February 2016

    Assuming you have updated to 1.5.4, the following show do it:

    {
      label: 'Upload:',
      name: ...,
      ajaxData: function ( d ) {
        d.append( 'site', id_establecimiento() ); // edit - use `d`
      },
      ...
    }
    

    Allan

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    I've updated the above post - the parameter passed in, d, is a FormData object so we need to use append.

    Allan

  • aneto2400aneto2400 Posts: 58Questions: 8Answers: 1

    Hi Allan,
    thank you your help.

    My tests on
    http://tripntry.com/x.samples/datateditor154/examples/advanced/upload.html

    Confirm that the sintax should be d.append() , because data.append() give me error (Uncaught ReferenceError: data is not defined) when I try to change the image on the editor form. Therefore, in my case sintax for ajaxData: are:

                            ajaxData: function ( d ) {
                                    d.append( 'site', id_establecimiento() );
                                            },
    

    After your answer I´ve to start from cero, this way to discard errors:
    1. I´ve to download last Datatable v.1.5.4, unzip and uplad to my test server

    1. I´ve done minimal changes in your upload.hml and upload.php code: Only incluide my fields, my columns and change labels inside <th></th> table.

    2. I dont touch rest of de code, neither JS, neither CSS.

    Now, when I used on ajax call:

      ajaxData: function ( d ) {d.append( 'site', id_establecimiento() ); 
    

    and on server-side:

       $site=$_POST['site'];
    

    dont work, ( it show none rows) , therefore I can´t edit image on table. Now on Chome debug don't appear errors.

    Obviously, if a fixed on server-side the value:

    $site="342800010";  
    

    its works, show the table and yes, I can to edit, new or delete the image on table.

    Any idea?.

    Thank you. Eduardo

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    You had this above:

         ajax: {
            url:"../php/upload.php",
            type: "POST",
            data: function ( d )    {
                d.site =  id_establecimiento(); //get id (site) after login
            }  
        }, 
    

    Add that back in first of all.

    Allan

  • aneto2400aneto2400 Posts: 58Questions: 8Answers: 1

    Hi Allan,
    If I understood well, I´ve left the JS code as first time. Current JS code (below) . Server-side code same that before. JSON output (below). None error on console (debug Chrome). The "site" value , same problem, don't pass :(

    Thank you for you help,
    Eduardo

      function id_establecimiento(results){
     var id_estblecmto = localStorage.getItem('establecimiento');
    return id_estblecmto
      };
    
     var editor; // use a global for the submit and return data rendering in the examples
    
    $(document).ready(function() {
    
    editor = new $.fn.dataTable.Editor( {
    
        ajax: {
                  url:"../php/upload.php",
                  type: "POST",
                  data: function ( d )    {
                      d.site =  id_establecimiento(); //get id (site) after login
                  } 
              },
    
        table: "#example",
        fields: [ 
                        {
                            label: "Nombre (establecimiento):",
                            name: "nom_estbl",
                            status: "This field is required"
    
                        },
                        {
                            label: "Telefono:",
                            name: "telefono",
                            status: "This field is required"
    
                        },
                        {
                            label: "E-mail (establecimiento):",
                            name: "email_estbl",
                            status: "This field is required"
                        },                      
                        {
                            label: "Nº de Plazas:",
                            name: "num_plaz",
                            status: "This field is required"                        
                        },
                        {
                            label: "Precio medio:",
                            name: "prec_med"
                        },
                        {
                            label: "Site (ID):",
                            name: "site",
                            //type: "readonly",
                            def: id_establecimiento,
                        },
    
                        {
                            label: "Image:",
                            name: "image",
                            type: "upload",                                     
                            display: function ( file_id ) {
                                return '<img src="'+table.file( 'files', file_id ).web_path+'"/>';
                            },
                            clearText: "Clear",
                            noImageText: 'No image'
                        }
        ]
    
    } );
    
       alert (" site sent : "+id_establecimiento()); // only test
    
    var table = $('#example').DataTable( {
        dom: "Bfrtip",
        ajax: "../php/upload.php",
        columns: [
            { data: "nom_estbl" },
            { data: "telefono" },
            { data: "email_estbl" },
            { data: "num_plaz" },
            { data: "prec_med" },
            {
                data: "image",
                render: function ( file_id ) {
                    return file_id ?
                        '<img src="'+table.file( 'files', file_id ).web_path+'"/>' :
                        null;
                },
                defaultContent: "No image",
                title: "Image"
            }
        ],
        select: true,
        buttons: [
            { extend: "create", editor: editor },
            { extend: "edit",   editor: editor },
            { extend: "remove", editor: editor }
        ]
    } );
     } );
    

    JSON output:

     {data: [], options: [],…}
     data: []
     files: {files: {397: {id: "397", filename: "113.jpg", filesize: "15489", web_path:         "/upload/397.jpg",…}}}
     files: {397: {id: "397", filename: "113.jpg", filesize: "15489", web_path:   "/upload/397.jpg",…}}
      397: {id: "397", filename: "113.jpg", filesize: "15489", web_path: "/upload/397.jpg",  …}
      options: []
    
  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Try the following for your upload field type:

     
                        {
                            label: "Image:",
                            name: "image",
                            type: "upload",                                    
                            display: function ( file_id ) {
                                return '<img src="'+table.file( 'files', file_id ).web_path+'"/>';
                            },
                            clearText: "Clear",
                            ajaxData: function ( d ) {d.append( 'site', id_establecimiento() );
                            noImageText: 'No image'
                        }
    

    Allan

  • aneto2400aneto2400 Posts: 58Questions: 8Answers: 1

    Hi Allan,
    Than you for you help.

    No resolve, same results (same JSON output and none errors on console).

    PD: I've added on ajaxData a curly bracket at end of line, because give me error of sintax, It´s correct? (below)

    Regards, Eduardo

                        {
                            label: "Image:",
                            name: "image",
                            type: "upload",                                   
                            display: function ( file_id ) {
                                return '<img src="'+table.file( 'files', file_id ).web_path+'"/>';
                            },
                            clearText: "Clear",
                            ajaxData: function ( d ) {d.append( 'site', id_establecimiento() );}, // here I´ve add  " }, "
                            noImageText: 'No image'
                        },
    
  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    If I load your page and attempt to upload a picture I can see the following in the data submitted to the server:

    ------WebKitFormBoundaryAXVeADEWWGuzOrDR
    Content-Disposition: form-data; name="site"
    
    null
    

    So site is being added to the request. But id_establecimiento() is returning null (which you can confirm by simply running id_establecimiento() on the console in your browser).

    Allan

  • aneto2400aneto2400 Posts: 58Questions: 8Answers: 1

    Hi Allan,

    If I run id_establecimiento() on console it give me the site value (below , console output). What's the next step for to resolve this issue ? .

    Thank you, Eduardo

    > id_establecimiento()
    > "342800010"
    > 
    
  • aneto2400aneto2400 Posts: 58Questions: 8Answers: 1

    Hi Allan,

    Give you more info with more tests: on current state when I going to create a new row (button New) , I fill fields, "Choose file.." (pick up a image) and give "Create", appear a error on chrome console and the form is stopped ( keep frozeen ) . Perhaps this help us to resolve the problem.

    The console error said:

    Uncaught TypeError: Cannot read property 'id' of undefined

    and chrome console to show dataTables.editor.min.js:58 , on this line apper a function (below) and underline where function crash, on this point : k.push(b.upload.id)

     k.push(b.upload.id),n<c.length-1?(n++,o.readAsDataURL(c[n])):(j.call(a,k),z&&a.submit()))}}))};o.readAsDataURL(c[0])};f.prototype._constructor=function(a){a=
    

    Thank you, Eduardo

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Hi Eduardo,

    With the change to have id_establecimiento() return a number, I can now successfully upload a file. I don't see any errors when I upload an image and the image is correctly shown in the from once uploaded.

    Allan

  • aneto2400aneto2400 Posts: 58Questions: 8Answers: 1

    Hi Allan,

    I´m happy to listen your message, but I have the same problem. Today I´ve test again from differents PCs and differentes browsers (before I´ve cleaned all cache of that browser) and appear the same error. I ´ve capture the error and you can see on:
    http://tripntry.com/x.samples/datateditor154/examples/advanced/issues/001_error_upload_new_file.png

    I´m sorry, but how it can to be?. Can you test again? (please clean your browser cache). I remember you the link:
    http://tripntry.com/x.samples/datateditor154/examples/advanced/upload.html

    Thank you, Eduardo

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Hi Eduardo,

    To confirm, the issue is no longer not being able to upload a file, but once you upload a file you then can't submit the form. Is that correct?

    If so, could you update to the just released Editor 1.5.5 please. That release fixes a bug whereby the success handler for the upload was incorrectly being triggered by the main form.

    Allan

  • aneto2400aneto2400 Posts: 58Questions: 8Answers: 1

    Hi Allan,

    I describe step-by-step the secuence in the form and what happend in DB-tables and the ./upload/ folder . If you see that my description it match with your words, yes i have the issue and therefore I´ll go to 1.5.5, of course.

    My secuence:

    • Press "New" button, open the form and I fill the form fields, after press "Chose file..." button and pick up an image, the image show on form.
    • When i press "Create" button , the form frozen and circle spinning whithout stop. Appear the error (console): Uncaught TypeError: Cannot read property 'id' of undefined, that to point to dataTables.editor.min.js:58 and inside it, to point to ...k.push(b.upload.id)... (same that before comments )
    • On my DB table "files" (images) , write a row with all fields . OK
    • On my DB table "r_clientes" (users) don't write on image field. The field es empty (NULL). BAD
    • The image file is upload to ./upload/ folder. OK
    • I close the form. Nothing changes on DB tables.

    Sounds the secuence might match with the bug?

    Thank you!, Eduardo

  • aneto2400aneto2400 Posts: 58Questions: 8Answers: 1

    Hi Allan,

    I´ve loaded v.1.5.5 on my test server and now write image field on DB table "r_clientes" (users), but now (new issue) the table HTML don't show nothing.

    I´ve came back to use old sintax on Ajax call,and now Its works!!!!.
    Below the JS code that work.

    Now my question are: this sintax is supported on v.1.5.5 without problems?

    PD:
    1. I need use variable "site" the AJAX call on form and also on table, if not dont work. 2. None changes are required on upload.php

    Comments are welcome.

    Thanks, Eduardo

     // abajo, MUY IMPORTANTE , es la funcion que devuelve el ID_establec a {site:...} ,en    las llamadas JSON 
     function id_establecimiento(results){
     var id_estblecmto = localStorage.getItem('establecimiento');
    return id_estblecmto
    };
    
    var editor; // use a global for the submit and return data rendering in the examples
    
    $(document).ready(function() {
    editor = new $.fn.dataTable.Editor( {
        //ajax: "../php/upload.php",
         ajax: {
            url:"../php/upload.php",
            type: "POST",
            data: function ( d )    {
                // ¡¡¡ Personalizar el site para cada cliente!!!!
                d.site =  id_establecimiento(); //llamada a mi funct. Recupero el (ID), guardado tras logarse
                                    }   
                },  
        table: "#example",
        fields: [ 
                        {
                            label: "Nombre (establecimiento):",
                            name: "nom_estbl",
                            status: "This field is required"
    
                        },
                        {
                            label: "Telefono:",
                            name: "telefono",
                            status: "This field is required"
    
                        },
                        {
                            label: "E-mail (establecimiento):",
                            name: "email_estbl",
                            status: "This field is required"
                        },
    
                        {
                            label: "Nº de Plazas:",
                            name: "num_plaz",
                            status: "This field is required"
    
                        },
                        {
                            label: "Precio medio:",
                            name: "prec_med"
                        },
                        {
                            label: "Site (ID):",
                            name: "site",
                            //type: "readonly",
                            def: id_establecimiento,
                        },
                        {
                            label: "Image:",
                            name: "image",
                            type: "upload",
                            display: function ( file_id ) {
                                return '<img src="'+table.file( 'files', file_id ).web_path+'"/>';
                            },
                            clearText: "Clear",
                            //ajaxData: function ( d ) {d.append( 'site',     id_establecimiento() );}, // no work
                            noImageText: 'No image'
                        }
         ]
      } );
    
        //alert (" site sent : "+id_establecimiento()); // only test
    
    
    var table = $('#example').DataTable( {
        dom: "Bfrtip",
        //ajax: "../php/upload.php",
         ajax: {
            url:"../php/upload.php",
            type: "POST",
            data: function ( d )    {
                // ¡¡¡ Personalizar el site para cada cliente!!!!
                d.site =  id_establecimiento(); //llamada a mi funct. Recupero el (ID), guardado tras logarse
                                    }   
                },  
        columns: [
            { data: "nom_estbl" },
            { data: "telefono" },
            { data: "email_estbl" },
            { data: "num_plaz" },
            { data: "prec_med" },
            {
                data: "image",
                render: function ( file_id ) {
                    return file_id ?
                        '<img src="'+table.file( 'files', file_id ).web_path+'"/>' :
                        null;
                },
                defaultContent: "No image",
                title: "Image"
            }
        ],
        select: true,
        buttons: [
            { extend: "create", editor: editor },
            { extend: "edit",   editor: editor },
            { extend: "remove", editor: editor }
        ]
    } );
    

    } );

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Answer ✓

    Hi Eduardo,

    Good to hear that 1.5.5. helped! I've just tried the example at: http://tripntry.com/x.samples/datateditor155/examples/advanced/upload.html and it appears to work well. I can add a new row, upload and delete the test row I created.

    The syntax above looks correct and everything appears to work now. Can you confirm that is the case for you as well?

    Thanks,
    Allan

  • aneto2400aneto2400 Posts: 58Questions: 8Answers: 1

    Hi Allan,

    Yes, that is the example that works and yes, you can close this case

    Thank you very much for you help.

    Regards, Eduardo

This discussion has been closed.