douzhao2047 2019-01-06 19:43
浏览 83
已采纳

按钮单击不返回数据或初始化模态

I have created a form to display all records from my database with the ability to add a new user, edit, and delete. The delete works fine. However, the add and edit functions are supposed to show a bootstrap modal with either blank fields for the add user, or all the information to edit a user. The modal isn't appearing and I can't understand why. There are no errors displayed in the console. I know I have the correct database configuration since the delete function works.

Driving me crazy :)

I've attached my code to see if anyone knows what I'm missing.

Thanks!!

profile.php

<!DOCTYPE html>
<html lang="en">
<head>
<title>Staff Profile Form</title>

<meta charset="utf-8">
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<script src = "jquery/jquery-3.3.1.js"></script>

<script>
// Update the users data list
function getUsers(){
$.ajax({
    type: 'POST',
    url: 'userAction.php',
    data: 'action_type=view',
    success:function(html){
        $('#userData').html(html);
    }
});
}

// Send CRUD requests to the server-side script
function userAction(type, id){
id = (typeof id == "undefined")?'':id;
var userData = '', frmElement = '';
if(type == 'add'){
    frmElement = $("#modalUserAddEdit");
    userData = 
frmElement.find('form').serialize()+'&action_type='+type+'&id='+id;
}else if (type == 'edit'){
    frmElement = $("#modalUserAddEdit");
    userData = frmElement.find('form').serialize()+'&action_type='+type;
}else{
    frmElement = $(".row");
    userData = 'action_type='+type+'&id='+id;
}
frmElement.find('.statusMsg').html('');
$.ajax({
    type: 'POST',
    url: 'userAction.php',
    dataType: 'JSON',
    data: userData,
    beforeSend: function(){
        frmElement.find('form').css("opacity", "0.5");
    },
    success:function(resp){
        frmElement.find('.statusMsg').html(resp.msg);
        if(resp.status == 1){
            if(type == 'add'){
                frmElement.find('form')[0].reset();
            }
            getUsers();
        }
        frmElement.find('form').css("opacity", "");
    }
});
}

// Fill the user's data in the edit form
function editUser(id){
$.ajax({
    type: 'POST',
    url: 'userAction.php',
    dataType: 'JSON',
    data: 'action_type=data&id='+id,
    success:function(data){
        $('#id').val(data.id);
        $('#name').val(data.name);
        $('#location').val(data.location);
        $('#specialty').val(data.specialty);
    }
});
}

// Actions on modal show and hidden events
$(function(){
$('#modalUserAddEdit').on('show.bs.modal', function(e){
    var type = $(e.relatedTarget).attr('data-type');
    var userFunc = "userAction('add');";
    if(type == 'edit'){
        userFunc = "userAction('edit');";
        var rowId = $(e.relatedTarget).attr('rowID');
        editUser(rowId);
    }
    $('#userSubmit').attr("onclick", userFunc);
});

$('#modalUserAddEdit').on('hidden.bs.modal', function(){
    $('#userSubmit').attr("onclick", "");
    $(this).find('form')[0].reset();
    $(this).find('.statusMsg').html('');
});
});
</script>


</head>
<body>


<?php
// Include and initialize DB class
require_once 'db.php';
$db = new DB();

// Fetch the users data
$users = $db->getRows('monctonfir');
?>
<div class="container">
<div class="row">
    <div class="col-md-12 head">
        <h5>Users</h5>
        <!-- Add link -->
        <div class="float-right">
            <a href="javascript:void(0);" class="btn btn-success" data- 
 type="add" data-toggle="modal" data-target="#modalUserAddEdit"><i 
class="plus"></i> New User</a>
        </div>
    </div>
    <div class="statusMsg"></div>
    <!-- List the users -->
    <table class="table table-striped table-bordered">
        <thead class="thead-dark">
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Location</th>
                <th>Specialty</th>

                <th>Profile Image</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody id="userData">
            <?php if(!empty($users)){ foreach($users as $row){ ?>
            <tr>
                <td><?php echo '#'.$row['id']; ?></td>
                <td><?php echo $row['name']; ?></td>
                <td><?php echo $row['location']; ?></td>
                <td><?php echo $row['specialty']; ?></td>

                <td><?php echo $row['file']; ?></td>
                <td>
                    <a href="javascript:void(0);" class="btn btn-warning" rowID = "<?php echo $row['id']; ?>" data-type="edit" data-toggle="modal" data-target="#modalUserAddEdit">UPDATE</a>
                    <a href="javascript:void(0);" class="btn btn-danger" onclick="return confirm('Are you sure to delete data?')?userAction('delete', '<?php echo $row['id']; ?>'):false;">DELETE</a>

                </td>
            </tr>
            <?php } }else{ ?>
            <tr><td colspan="5">No user(s) found...</td></tr>
            <?php } ?>
        </tbody>
    </table>
   </div>
</div>



<!-- Modal Add and Edit Form -->
<div class="modal fade" id="modalUserAddEdit" role="dialog">
<div class="modal-dialog">
    <div class="modal-content">
        <!-- Modal Header -->
        <div class="modal-header">
          <h4 class="modal-title">Add New User</h4>
          <button type="button" class="close" data-dismiss="modal">&times; 
 </button>
        </div>

        <!-- Modal Body -->
        <div class="modal-body">
            <div class="statusMsg"></div>
            <form role="form">
                <div class="form-group">
                    <label for="name">Name</label>
                    <input type="text" class="form-control" name="name" id="name" placeholder="Enter your name">
                </div>
                <div class="form-group">
                    <label for="location">Location</label>
                    <input type="text" class="form-control" name="location" id="location" placeholder="Enter your work site">
                </div>
                <div class="form-group">
                    <label for="specialty">Specialty</label>
                    <input type="text" class="form-control" name="specialty" id="specialty" placeholder="Enter your specialty">
                </div>

                <input type="hidden" class="form-control" name="id" id="id"/>
            </form>
        </div>

        <!-- Modal Footer -->
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-success" id="userSubmit">SUBMIT</button>
        </div>
    </div>
 </div>
</div>

</body>
</html>

userAction.php

<?php
// Include and initialize DB class
require_once 'DB.php';
$db = new DB();

// Database table name
$tblName = 'monctonfir';

// If the form is submitted
if(!empty($_POST['action_type'])){
if($_POST['action_type'] == 'data'){
    // Fetch data based on row ID
    $conditions['where'] = array('id' => $_POST['id']);
    $conditions['return_type'] = 'single';
    $user = $db->getRows($tblName, $conditions);

    // Return data as JSON format
    echo json_encode($user);
}elseif($_POST['action_type'] == 'view'){
    // Fetch all records
    $users = $db->getRows($tblName);

    // Render data as HTML format
    if(!empty($users)){
        foreach($users as $row){
            echo '<tr>';
            echo '<td>#'.$row['id'].'</td>';
            echo '<td>'.$row['name'].'</td>';
            echo '<td>'.$row['location'].'</td>';
            echo '<td>'.$row['specialty'].'</td>';
            echo '<td><a href="javascript:void(0);" class="btn btn-warning" rowID="'.$row['id'].'" data-type="edit" data-toggle="modal" data-target="#modalUserAddEdit">edit</a>
            <a href="javascript:void(0);" class="btn btn-danger" onclick="return confirm(\'Are you sure to delete data?\')?userAction(\'delete\', \''.$row['id'].'\'):false;">delete</a></td>';
            echo '</tr>';
        }
    }else{
        echo '<tr><td colspan="5">No user(s) found...</td></tr>';
    }
}elseif($_POST['action_type'] == 'add'){
    $msg = '';
    $status = $verr = 0;

    // Get user's input
    $name = $_POST['name'];
    $location = $_POST['location'];
    $specialty = $_POST['specialty'];


    // Validate form fields
    if(empty($name)){
        $verr = 1;
        $msg .= 'Please enter your name.<br/>';
    }
    if(empty($location) || !filter_var($email, FILTER_VALIDATE_EMAIL)){
        $verr = 1;
        $msg .= 'Please enter your work site.<br/>';
    }
    if(empty($specialty)){
        $verr = 1;
        $msg .= 'Please enter your specialty.<br/>';
    }


    if($verr == 0){
        // Insert data in the database
        $userData = array(
            'name'  => $name,
            'location' => $location,
            'specialty' => $specialty,

        );
        $insert = $db->insert($tblName, $userData);

        if($insert){
            $status = 1;
            $msg .= 'User data has been inserted successfully.';
        }else{
            $msg .= 'Some problem occurred, please try again.';
        }
    }

    // Return response as JSON format
    $alertType = ($status == 1)?'alert-success':'alert-danger';
    $statusMsg = '<p class="alert '.$alertType.'">'.$msg.'</p>';
    $response = array(
        'status' => $status,
        'msg' => $statusMsg
    );
    echo json_encode($response);
}elseif($_POST['action_type'] == 'edit'){
    $msg = '';
    $status = $verr = 0;

    if(!empty($_POST['id'])){
        // Get user's input
        $name = $_POST['name'];
        $location = $_POST['location'];
        $specialty = $_POST['specialty'];
        $location = $_POST['location'];


        // Validate form fields
        if(empty($name)){
            $verr = 1;
            $msg .= 'Please enter your name.<br/>';
        }
        if(empty($location)){
            $verr = 1;
            $msg .= 'Please enter a your work site.<br/>';
        }
        if(empty($specialty)){
            $verr = 1;
            $msg .= 'Please enter your specialty<br/>';
        }


        if($verr == 0){
            // Update data in the database
            $userData = array(
                'name'  => $name,
                'location' => $location,
                'specialty' => $specialty,

            );
            $condition = array('id' => $_POST['id']);
            $update = $db->update($tblName, $userData, $condition);

            if($update){
                $status = 1;
                $msg .= 'User data has been updated successfully.';
            }else{
                $msg .= 'Some problem occurred, please try again.';
            }
        }
    }else{
        $msg .= 'Some problem occurred, please try again.';
    }

    // Return response as JSON format
    $alertType = ($status == 1)?'alert-success':'alert-danger';
    $statusMsg = '<p class="alert '.$alertType.'">'.$msg.'</p>';
    $response = array(
        'status' => $status,
        'msg' => $statusMsg
    );
    echo json_encode($response);
}elseif($_POST['action_type'] == 'delete'){
    $msg = '';
    $status = 0;

    if(!empty($_POST['id'])){
        // Delate data from the database
        $condition = array('id' => $_POST['id']);
        $delete = $db->delete($tblName, $condition);

        if($delete){
            $status = 1;
            $msg .= 'User data has been deleted successfully.';
        }else{
            $msg .= 'Some problem occurred, please try again.';
        }
    }else{
        $msg .= 'Some problem occurred, please try again.';
    }  

    // Return response as JSON format
    $alertType = ($status == 1)?'alert-success':'alert-danger';
    $statusMsg = '<p class="alert '.$alertType.'">'.$msg.'</p>';
    $response = array(
        'status' => $status,
        'msg' => $statusMsg
    );
    echo json_encode($response);
  }
}

exit;
?>
  • 写回答

1条回答 默认 最新

  • duanchao4445 2019-01-06 20:05
    关注

    Bootstrap lists modals under components requiring JavaScript (i.e. bootstrap.min.js) take a look at the docs: https://getbootstrap.com/docs/4.0/getting-started/introduction/ Try adding this before the closing body tag:

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元