не может просмотреть таблицы данных AJAX JSON в PHP - PullRequest
0 голосов
/ 01 июня 2018

Я попробовал свои коды для просмотра данных из базы данных phpmyadmin, но они не работают.стол не покажет.но когда я добавляю данные в форму добавления, данные были успешно добавлены в мою базу данных.к сожалению это не может быть просмотрено в моей таблице данных. это мой результат, говорящий о том, что в таблицах данных нет данных

service.php

<?php

include('database_connection.php');

include('function.php');

if(!isset($_SESSION['type']))
{
    header('location:login.php');
}

include('header.php');


?>
    <link rel="stylesheet" href="css/datepicker.css">
    <script src="js/bootstrap-datepicker1.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>

    <script>
    $(document).ready(function(){
        $('#service_history_date').datepicker({
            format: "yyyy-mm-dd",
            autoclose: true
        });
    });
    </script>

    <span id="alert_action"></span>
    <div class="row">
        <div class="col-lg-12">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <div class="row">
                        <div class="col-md-10">
                            <h3 class="panel-title">Car List</h3>
                        </div>
                        <div class="col-md-2" align="right">
                            <button type="button" name="add" id="add_button" data-toggle="modal" data-target="#serviceModal" class="btn btn-success btn-xs">Add</button>
                        </div>
                    </div>
                </div>
                <div class="panel-body">
                    <table id="service_data" class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>Service ID</th>
                                <th>Car Plate No.</th>
                                <th>Car Mileage</th>
                                <th>Service Date</th>
                                <th>Service Type</th>
                                <th>Serviced By</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div id="serviceModal" class="modal fade">
        <div class="modal-dialog">
            <form method="post" id="service_form">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                          <h4 class="modal-title"><i class="fa fa-plus"></i> Add New Service Record</h4>
                    </div>
                    <div class="modal-body">
                                    <div class="form-group">
                                        <label>Choose Car Plate No</label>
                                    <select name="carPlateNo" id="carPlateNo" class="form-control" required />
                                        <option value="">Select Car Plate No</option>
                                        <?php echo fill_carPlateNo_service($connect); ?>
                                    </select>
                                </div>
                                    <div class="form-group">
                                        <label>Enter Current Mileage</label>
                                    <input type="text" name="carOdometer" id="carOdometer" class="form-control" required />
                                </div>
                                    <div class="form-group">
                                        <label>Service Date</label>
                                        <input type="text" name="service_history_date" id="service_history_date" class="form-control" required />
                                    </div>
                                    <div class="form-group">
                                        <label>Service Type</label>
                                        <select name="serviceType" id="serviceType" class="form-control" required>
                                        <option value="">Select Service Type</option>
                                        <?php echo fill_serviceType_service($connect); ?>
                                    </select>
                                  </div>

                                    <div class="form-group">
                                        <label>Serviced By</label>
                                        <select name="staff_id" id="staff_id" class="form-control" required>
                                        <option value="">Select Serviced By Staff Name</option>
                                        <?php echo fill_staff_service($connect); ?>
                                    </select>
                                  </div>
                        </div>
                        </div>
                    <div class="modal-footer">
                        <input type="hidden" name="service_history_id" id="service_history_id" />
                        <input type="hidden" name="btn_action" id="btn_action" />
                        <input type="submit" name="action" id="action" class="btn btn-info" value="Add" />
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>

            </form>
        </div>
        </div>



        <script>
        $(document).ready(function(){

            $('#add_button').click(function(){
                $('#serviceModal').modal('show');
                $('#service_form')[0].reset();
                $('.modal-title').html("<i class='fa fa-plus'></i> Add car");
                $('#action').val('Add');
                $('#btn_action').val('Add');
            });

            $(document).on('submit','#service_form', function(event){
                event.preventDefault();
                $('#action').attr('disabled','disabled');
                var form_data = $(this).serialize();
                $.ajax({
                    url:"service_action.php",
                    method:"POST",
                    data:form_data,
                    success:function(data)
                    {
                        $('#service_form')[0].reset();
                        $('#serviceModal').modal('hide');
                        $('#alert_action').fadeIn().html('<div class="alert alert-success">'+data+'</div>');
                        $('#action').attr('disabled', false);
                        servicedataTable.ajax.reload();
                    }
                })
            });

            $(document).on('click', '.update', function(){
                var car_id = $(this).attr("id");
                var btn_action = 'fetch_single';
                $.ajax({
                    url:'service_action.php',
                    method:"POST",
                    data:{service_history_id:service_history_id, btn_action:btn_action},
                    dataType:"json",
                    success:function(data)
                    {
                        $('#serviceModal').modal('show');
                        $('#service_history_id').val(data.service_history_id);
                        $('#car_name').val(data.car_name);
                        $('.modal-title').html("<i class='fa fa-pencil-square-o'></i> Edit car");
                        $('#car_id').val(car_id);
                        $('#action').val('Edit');
                        $('#btn_action').val('Edit');
                    }
                })
            });

            $(document).on('click','.delete', function(){
                var car_id = $(this).attr("id");
                var status  = $(this).data('status');
                var btn_action = 'delete';
                if(confirm("Are you sure you want to change status?"))
                {
                    $.ajax({
                        url:"service_action.php",
                        method:"POST",
                        data:{car_id:car_id, status:status, btn_action:btn_action},
                        success:function(data)
                        {
                            $('#alert_action').fadeIn().html('<div class="alert alert-info">'+data+'</div>');
                            servicedataTable.ajax.reload();
                        }
                    })
                }
                else
                {
                    return false;
                }
            });


            var servicedataTable = $('#service_data').DataTable({
                "processing":true,
                "serverSide":true,
                "order":[],
                "ajax":{
                    url:"service_fetch.php",
                    type:"POST"
                },
                "columnDefs":[
                    {
                        "targets":[4, 5],
                        "orderable":false,
                    },
                ],
                "pageLength": 10
            });

        });
        </script>


        <?php
        include('footer.php');
        ?>

service_fetch.php

<?php

//service_fetch.php

include('database_connection.php');

include('function.php');

$query = '';

$output = array();

$query .= "
SELECT * FROM service_history
INNER JOIN car ON car.car_id = service_history.carPlateNo
INNER JOIN serviceType ON serviceType.service_id = service_history.serviceType
INNER JOIN staff ON staff.staff_id = service_history.staff_id
";


if(isset($_POST["search"]["value"]))
{
    $query .= '(service_history_id LIKE "%'.$_POST["search"]["value"].'%" ';
    $query .= 'OR serviceType LIKE "%'.$_POST["search"]["value"].'%" ';
    $query .= 'OR carPlateNo LIKE "%'.$_POST["search"]["value"].'%" ';
    $query .= 'OR staff_id LIKE "%'.$_POST["search"]["value"].'%" ';
    $query .= 'OR service_history_date LIKE "%'.$_POST["search"]["value"].'%") ';
}

if(isset($_POST["order"]))
{
    $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
    $query .= 'ORDER BY service_history_id DESC ';
}

if($_POST["length"] != -1)
{
    $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}

$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();

foreach($result as $row)

{
    $sub_array = array();
    $sub_array[] = $row['service_history_id'];
    $sub_array[] = $row['carPlateNo'];
    $sub_array[] = $row['carOdometer'];
    $sub_array[] = $row['service_history_date'];
    $sub_array[] = $row['serviceType'];
    $sub_array[] = $row['staff_id'];
    $data[] = $sub_array;
}

function get_total_all_records($connect)
{
    $statement = $connect->prepare("SELECT * FROM service_history");
    $statement->execute();
    return $statement->rowCount();
}

$output = array(
    "draw"              =>  intval($_POST["draw"]),
    "recordsTotal"      =>  $filtered_rows,
    "recordsFiltered"   =>  get_total_all_records($connect),
    "data"              =>  $data
);

echo json_encode($output);

?>

service_action.php

<?php

//brand_action.php
include('database_connection.php');

if(isset($_POST['btn_action']))
{
    if($_POST['btn_action'] == 'Add')
    {
        $query = "
        INSERT INTO service_history (carPlateNo, carOdometer, 
        service_history_date, serviceType, staff_id)
        VALUES (:carPlateNo, :carOdometer, :service_history_date, 
        :serviceType, :staff_id)
        ";
        $statement = $connect->prepare($query);
        $statement->execute(
            array(
                ':carPlateNo'       =>  $_POST["carPlateNo"],
              ':carOdometer'        =>  $_POST["carOdometer"],
                ':service_history_date'     =>  date("Y-m-d"),
                ':serviceType'      =>  $_POST["serviceType"],
                ':staff_id'     =>  $_POST["staff_id"]
            )
        );
        $result = $statement->fetchAll();
        if(isset($result))
        {
            echo 'New Serviced Car Added';
        }
    }

    if($_POST['btn_action'] == 'fetch_single')
    {
        $query = "
        SELECT * FROM service_history WHERE service_history_id = 
        :service_history_id
        ";
        $statement = $connect->prepare($query);
        $statement->execute(
            array(
                ':service_history_id'   =>  $_POST["service_history_id"]
            )
        );
        $result = $statement->fetchAll();
        foreach($result as $row)
        {
            $output['carPlateNo'] = $row['carPlateNo'];
            $output['carOdometer'] = $row['carOdometer'];
            $output['service_history_date'] = $row['service_history_date'];
            $output['serviceType'] = $row['serviceType'];
            $output['staff_id'] = $row['staff_id'];

        }
        echo json_encode($output);
    }


    if($_POST['btn_action'] == 'delete')
    {
        $status = 'active';
        if($_POST['status'] == 'active')
        {
            $status = 'inactive';
        }
        $query = "
        UPDATE car
        SET car_status = :car_status
        WHERE carPlateNo = :carPlateNo
        ";
        $statement = $connect->prepare($query);
        $statement->execute(
            array(
                ':carPlateNo'       =>  $_POST["carPlateNo"],
                ':car_status'   =>  $status

            )
        );
        $result = $statement->fetchAll();
        if(isset($result))
        {
            echo 'Car status changed to ' . $status;
        }
    }
}

?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...