DataTables con Ajax, PHP & MySQL

MrSipping

Nuovo Utente
2
0
Buongiorno a tutti, sto creando una DataTables per l'inserimento, la modifica e l'eliminazione dei dati. Ho praticamente "copiato" da questo sito https://webdamn.com/datatables-add-edit-delete-with-ajax-php-mysql/ però non capisco perchè non funzioni e non mi salvi neanche nel db che ho, il sito dovrà essere hostato su aruba e io sto usando i loro db, ma vedo che con questo metodo non riesco.

Siccome non posso allegare i file, chiedo a qualche buon'uomo se mi può aiutare tramite altri canali.

Grazie a tutti, Buonagiornata

LATO RICHIESTA:
Codice:
<?php
$servername = "******";
$username = "******";
$password = "******";
$dbname = "******";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
$object = new rms();
if(isset($_POST["action"]))
{
    if($_POST["action"] == 'fetch')
    {
        $order_column = array('ingr', 'costounit', 'costomax', 'unitmix', 'imb', 'fornt', 'cod', 'grp');
        $output = array();
        $main_query = "
        SELECT * FROM Magazzino ";
        $search_query = '';
        if(isset($_POST["search"]["value"]))
        {
            $search_query .= 'WHERE category_name LIKE "%'.$_POST["search"]["value"].'%" ';
            $search_query .= 'OR product_name LIKE "%'.$_POST["search"]["value"].'%" ';
            $search_query .= 'OR product_price LIKE "%'.$_POST["search"]["value"].'%" ';
            $search_query .= 'OR product_status LIKE "%'.$_POST["search"]["value"].'%" ';
        }
        if(isset($_POST["order"]))
        {
            $order_query = 'ORDER BY '.$order_column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
        }
        else
        {
            $order_query = 'ORDER BY product_id DESC ';
        }
        $limit_query = '';
        if($_POST["length"] != -1)
        {
            $limit_query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
        }
        $object->query = $main_query . $search_query . $order_query;
        $object->execute();
        $filtered_rows = $object->row_count();
        $object->query .= $limit_query;
        $result = $object->get_result();
        $object->query = $main_query;
        $object->execute();
        $total_rows = $object->row_count();
        $data = array();
        foreach($result as $row)
        {
            $sub_array = array();
            $sub_array[] = html_entity_decode($row["product_name"]);
            $sub_array[] = $object->cur . $row["product_price"];
            $sub_array[] = $row["category_name"];
            $status = '';
            if($row["product_status"] == 'Enable')
            {
                $status = '<button type="button" name="status_button" class="btn btn-primary btn-sm status_button" data-id="'.$row["product_id"].'" data-status="'.$row["product_status"].'">Enable</button>';
            }
            else
            {
                $status = '<button type="button" name="status_button" class="btn btn-danger btn-sm status_button" data-id="'.$row["product_id"].'" data-status="'.$row["product_status"].'">Disable</button>';
            }
            $sub_array[] = $status;
            $sub_array[] = '
            <div align="center">
            <button type="button" name="edit_button" class="btn btn-warning btn-circle btn-sm edit_button" data-id="'.$row["product_id"].'"><i class="fas fa-edit"></i></button>
            &nbsp;
            <button type="button" name="delete_button" class="btn btn-danger btn-circle btn-sm delete_button" data-id="'.$row["product_id"].'"><i class="fas fa-times"></i></button>
            </div>
            ';
            $data[] = $sub_array;
        }
        $output = array(
            "draw"              =>  intval($_POST["draw"]),
            "recordsTotal"      =>  $total_rows,
            "recordsFiltered"   =>  $filtered_rows,
            "data"              =>  $data
        );
          
        echo json_encode($output);
    }
    if($_POST["action"] == 'Add')
    {
        $error = '';
        $success = '';
        $data = array(
            ':ingr' =>  $_POST["ingr"],
            ':costounit'        =>  $_POST["costounit"]
            ':costomax' =>  $_POST["cosotmax"],
            ':unitmix'  =>  $_POST["unitmix"],
            ':imb'  =>  $_POST["imb"],
            ':fornt'    =>  $_POST["fornt"],
            ':cod'  =>  $_POST["cod"],
            ':grp'  =>  $_POST["grp"],
        );
        $object->query = "
        SELECT * FROM Magazzino
        WHERE ingr = :ingr
        AND costounit = :costounit
        AND costomax = :costomax
        AND unitmix = :unitmix
        AND imb = :imb
        AND fornt = :fornt
        AND cod = :cod
        AND grp = :grp
        ";
        $object->execute($data);
        if($object->row_count() > 0)
        {
            $error = '<div class="alert alert-danger">Product Already Exists</div>';
        }
        else
        {
            $data = array(
                ':ingr'     =>  $object->clean_input($_POST["ingr"]),
                ':costounit'    =>  $object->clean_input($_POST["costounit"]),
                ':costomax'     =>  $object->clean_input($_POST["costomax"]),
                ':unitmix'      =>  $object->clean_input($_POST["unitmix"]),
                ':imb'      =>  $object->clean_input($_POST["imb"]),
                ':fornt'        =>  $object->clean_input($_POST["fornt"]),
                ':cod'      =>  $object->clean_input($_POST["cod"]),
                ':grp'      =>  $object->clean_input($_POST["grp"]),
  
            );
            $object->query = "
            INSERT INTO Magazzino
            (ingr, costounit, costomax, unitmix, imb, fornt, cod, grp)
            VALUES (:ingr, :costounit, :costomax, :unitmix, :imb, :fornt, :cod, :grp)
            ";
            $object->execute($data);
            $success = '<div class="alert alert-success">Product Added</div>';
        }
        $output = array(
            'error'     =>  $error,
            'success'   =>  $success
        );
        echo json_encode($output);
    }
}
$conn->close();
?>

LATO CLIENT:

<!-- Page Content -->
               <span id="message"></span>
               <div class="content content-boxed">
                <!-- Invoice -->
                <div class="block block-rounded">
                    <div class="block-header block-header-default">
                        <div class="block-options-item">
                        <ul class="nav-main nav-main-horizontal">
                            <li class="nav-main-item">
                                <a class="btn-sm btn-outline-secondary" href="javascript:void(0)">
                                    <i class="far fa-file-excel"></i> IMPORTA DA XLS/XLSX
                                </a>
                            </li>
                            <li class="nav-main-item">
                                <a class="btn-sm btn-outline-secondary" href="javascript:void(0)">
                                    <i class="far fa-file-excel"></i> ESPORTA IN XLSX
                                </a>
                            </li>
                        </ul>
                    </div>
                        <div class="block-options-item">
                            <!-- Print Page functionality is initialized in Helpers.print() -->  
                            <li class="nav-main-item">
                                <button type="button"  class="btn-sm btn-primary" name="add" id="add" data-toggle="modal" data-target="#modal-default-fadein"><i class="fa fa-edit"></i> AGGIUNGI INGREDIENTE</button>
                            </li>
                        </div>
                    </div>
                    <div class="block-content block-content-full">
                        <!-- Table -->
                            <table id="mag"class="table table-bordered table-striped table-vcenter js-dataTable-full">
                                <thead>
                                    <tr>
                                        <th></th>
                                        <th>Ingrediente</th>
                                        <th>Costo unitario</th>
                                        <th>Costo massimo</th>
                                        <th>Unità</th>
                                        <th>Imballaggio</th>
                                        <th>Fornitore</th>
                                        <th>Codice</th>
                                        <th>Gruppo merceologico</th>
                                        <th></th>
                                    </tr>
                                </thead>
                            </table>
                        <!-- END Table -->
                        <!-- Footer -->
                        <p class="text-muted text-center my-5">
                            Thank you for doing business with us.
                        </p>
                        <!-- END Footer -->
                </div>
            </div>  
                  <!-- Fade In Default Modal -->
        <div  class="modal fade" id="modal-default-fadein" tabindex="-1" role="dialog" aria-labelledby="modal-default-fadein" aria-hidden="true">
            <div class="modal-dialog">
            <form method="POST" id="product_form"> 
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="modal_title">Aggiungi Ingrediente</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body pb-1">
                    <span id="form_message"></span>               
                                                <div class="form-group">
                                                       <label for="Ingrediente">Ingrediente</label>
                                                    <div class="input-group">
                                                        <div class="input-group-prepend">
                                                            <span class="input-group-text">
                                                                <i class="fa fa-carrot"></i>
                                                            </span>
                                                        </div>
                                                           <input type="text" class="form-control" id="ingr" name="ingr">
                                                    </div>    
                                                </div>
                                                <div class="form-group form-row">
                                               
                                                   <div class="col-6">
                                                    <label for="costo">Costo unitario di acquisto (IVA ESCLUSA)</label>
                                                     <div class="input-group">
                                                     <div class="input-group-prepend">
                                                         <span class="input-group-text">
                                                             <i class="fa fa-euro-sign"></i>
                                                         </span>
                                                     </div>
                                                        <input type="text" class="form-control" id="costounit" name="costounit">
                                                    </div>
                                                   </div>              
                                                 
                                                   <div class="col-6"> 
                                                    <label for="costomassimo">Costo prezzo massimo <br> (IVA ESCLUSA)</label>
                                                     <div class="input-group">
                                                     <div class="input-group-prepend">
                                                         <span class="input-group-text">
                                                             <i class="fa fa-euro-sign"></i>
                                                         </span>
                                                     </div>
                                                        <input type="text" class="form-control" id="costomax" name="costomax">
                                                    </div>
                                                  </div> 
                                                </div>
                                            <div class="form-group form-row">
                                                 <div class="col-6">
                                                       <label for="unita">Unità di misura</label>
                                                    <div class="input-group">
                                                        <div class="input-group-prepend">
                                                            <span class="input-group-text">
                                                                <i class="fa fa-balance-scale"></i>
                                                            </span>
                                                        </div>
                                                        <select class="form-control" id="unitmix" name="unitmix">
                                                            <option value="0">KG(chilogrammi)</option>
                                                            <option value="1">LT(litri)</option>
                                                            <option value="2">PZ(pezzi)</option>
                                                        </select>
                                                    </div> 
                                                 </div> 
                                                 <div class="col-6">
                                                    <label for="imballaggio">Imballaggio</label>
                                                 <div class="input-group">
                                                     <div class="input-group-prepend">
                                                         <span class="input-group-text">
                                                             <i class="fa fa-box"></i>
                                                         </span>
                                                     </div>
                                                     <select class="form-control" id="imb" name="imb">
                                                         <option value="0">Bancali</option>
                                                         <option value="1">Barattoli</option>
                                                         <option value="2">Bins</option>
                                                         <option value="3">Cartoni</option>
                                                         <option value="4">Casse</option>
                                                         <option value="5">Ceste</option>
                                                         <option value="6">Sacchi</option>
                                                         <option value="7">Scatole</option>
                                                         <option value="8">Confezione</option>
                                                         <option value="9">Vasetto</option>
                                                         <option value="10">Vaso</option>
                                                         <option value="11">Bottiglia</option>
                                                         <option value="11">Fusto</option>
                                                         <option value="12">Pezzi</option>
                                                         <option value="13">Squeezer</option>
                                                         <option value="14">Busta</option>
                                                         <option value="15">Dispenser</option>
                                                     </select>
                                                 </div> 
                                                </div> 
                                            </div>    
                                            <div class="form-group">
                                                <label for="forn">Fornitore</label>
                                             <div class="input-group">
                                                 <div class="input-group-prepend">
                                                     <span class="input-group-text">
                                                         <i class="fa fa-dolly"></i>
                                                     </span>
                                                 </div>
                                                    <input type="text" class="form-control" id="fornt" name="fornt">
                                             </div>    
                                         </div>
                                         <div class="form-group form-row">
                                            <div class="col-4">
                                                  <label for="codice">Codice prodotto</label>
                                               <div class="input-group">
                                                   <div class="input-group-prepend">
                                                       <span class="input-group-text">
                                                           <i class="fa fa-barcode"></i>
                                                       </span>
                                                   </div>
                                                   <input type="text" class="form-control" id="cod" name="cod">
                                               </div> 
                                            </div> 
                                            <div class="col-8">
                                               <label for="gruppo">Gruppo merceologico</label>
                                            <div class="input-group">
                                                <div class="input-group-prepend">
                                                    <span class="input-group-text">
                                                        <i class="fa fa-dice-d20"></i>
                                                    </span>
                                                </div>
                                                <select class="form-control" id="grp" name="grp">
                                                    <option value="0">Frutta</option>
                                                    <option value="1">Verdure</option>
                                                    <option value="2">Surgelati</option>
                                                    <option value="3">Carne</option>
                                                    <option value="4">Pesce</option>
                                                    <option value="5">Secco</option>
                                                    <option value="6">Scatolame</option>
                                                    <option value="7">Salumi</option>
                                                    <option value="8">Formaggio e Latticini</option>
                                                    <option value="9">Dolciumi</option>
                                                    <option value="10">Bevande Alcoliche</option>
                                                    <option value="11">Bevande Analcoliche</option>
                                                </select>
                                            </div> 
                                           </div> 
                                       </div>    
                    </div>
                        <div class="modal-footer">
                            <input type="hidden" name="hidden_id" id="hidden_id" />
                            <input type="hidden" name="action" id="action" value="Aggiungi" />     
                            <input type="submit" name="submit" id="sumbit_button" class="btn btn-sm btn-hero-success" value="Aggiungi" />
                            <button type="button" class="btn btn-sm btn-secondary" data-dismiss="modal">Close</button>                                              
                        </div>
                </div>
              </form>
            </div>
        </div>
        <!-- END Fade In Default Modal -->
              
                <!-- END Invoice -->
            </div>
            <!-- END Page Content -->
            </main>
            <!-- END Main Container -->
<script>
$(document).ready(function(){
    var dataTable = $('#Magazzino').DataTable({
        "processing" : true,
        "serverSide" : true,
        "order" : [],
        "ajax" : {
            url:"../test/production_action.php",
            type:"POST",
            dat:{action:'fetch'}
        },
        "columnDefs":[
            {
                "targets":[0,9],
                "orderable":false,
            },
        ],
    });
    $('#add').click(function(){
      
        $('#product_form')[0].reset();
        $('#product_form').parsley().reset();
        $('#modal_title').text('Aggiungi Ingrediente');
        $('#action').val('Aggiungi');
        $('#submit_button').val('Aggiungi');
        $('#modal-default-fadein').modal('show');
        $('#form_message').html('');
    });
    $('#product_form').parsley();
    $('#product_form').on('submit', function(event){
        event.preventDefault();
        if($('#product_form').parsley().isValid())
        {     
            $.ajax({
                url:"../test/product_action.php",
                method:"POST",
                data:$(this).serialize(),
                dataType:'json',
                beforeSend:function()
                {
                    $('#submit_button').attr('disabled', 'disabled');
                    $('#submit_button').val('wait...');
                },
                success:function(data)
                {
                    $('#submit_button').attr('disabled', false);
                    if(data.error != '')
                    {
                        $('#form_message').html(data.error);
                        $('#submit_button').val('Add');
                    }
                    else
                    {
                        $('#modal-default-fadein').modal('hide');
                        $('#message').html(data.success);
                        dataTable.ajax.reload();
                        setTimeout(function(){
                            $('#message').html('');
                        }, 5000);
                    }
                }
            })
        }
    });
});
</script>
Grazie per l'aiuto
 
Ultima modifica da un moderatore:

DispatchCode

Moderatore
Staff Forum
Utente Èlite
1,563
1,207
CPU
Intel I9-10900KF 3.75GHz 10x 125W
Dissipatore
Gigabyte Aorus Waterforce X360 ARGB
Scheda Madre
Asus 1200 TUF Z590-Plus Gaming ATX DDR4
HDD
1TB NVMe PCI 3.0 x4, 1TB 7200rpm 64MB SATA3
RAM
DDR4 32GB 3600MHz CL18 ARGB
GPU
Nvidia RTX 3080 10GB DDR6
Audio
Integrata 7.1 HD audio
Monitor
LG 34GN850
PSU
Gigabyte P850PM
Case
Phanteks Enthoo Evolv X ARGB
Periferiche
MSI Vigor GK30, mouse Logitech
Net
30Mbps/3Mbps con Eolo
OS
Windows 10 64bit
Benvenuto! Il forum comunque non funziona così... e difficilmente troverai qualcuno che ti aiuti in pvt.
Se si tratta di codice lato client puoi postare tutto. Per il lato server anche, alla fine dovrai solo nascondere eventuali dati sensibili (utente e password remote e cose di questo tipo).

Quindi, ricapitolando:
  • pubblica la parte di codice interessata
  • verifica il motivo per il quale non funziona: ti dà errore? Hai guardato in console? Hai verificato errori lato server? Usa anche il debugger
 
  • Mi piace
Reazioni: Mursey

DispatchCode

Moderatore
Staff Forum
Utente Èlite
1,563
1,207
CPU
Intel I9-10900KF 3.75GHz 10x 125W
Dissipatore
Gigabyte Aorus Waterforce X360 ARGB
Scheda Madre
Asus 1200 TUF Z590-Plus Gaming ATX DDR4
HDD
1TB NVMe PCI 3.0 x4, 1TB 7200rpm 64MB SATA3
RAM
DDR4 32GB 3600MHz CL18 ARGB
GPU
Nvidia RTX 3080 10GB DDR6
Audio
Integrata 7.1 HD audio
Monitor
LG 34GN850
PSU
Gigabyte P850PM
Case
Phanteks Enthoo Evolv X ARGB
Periferiche
MSI Vigor GK30, mouse Logitech
Net
30Mbps/3Mbps con Eolo
OS
Windows 10 64bit

sp3ctrum

Amministratore
Staff Forum
13,045
5,381
CPU
AMD Ryzen 5 3900X
Dissipatore
Scythe Mugen 5 rev.b Push&Pull
Scheda Madre
ASUS TUF Gaming B550M-Plus WIFI
HDD
Nvme Samsung EVO 1Tb + SSD Samsung evo 850 250gb + Toshiba P300 3Tb
RAM
G.Skill 16gb Ripjaws V 3200Mhz + HyperX FURY 16gb 3200Mhz
GPU
KFA2 RTX 3060 Ti OC
Audio
Topping DX3 Pro + Focusrite Scarlett 2i2 + Mackie MR524 + Beyer DT 770 Pro
Monitor
LG Ultragear 27gp850
PSU
FSP Raider 650W 80+ Silver
Case
Thermaltake V200 RGB
Net
Vodafone 1000Mb
OS
Windows 10
Ho corretto io, la prossima volta usa i tag come ti hanno suggerito
 

Entra

oppure Accedi utilizzando