使用模态确认PHP删除所选项目

时间:2015-09-25 13:50:21

标签: php mysql ajax modal-dialog

我有 index.php 代码:

<form role="form" id="submit_form" class="form-horizontal">

                <div class="panel-body">
                  <div class="form-group has-feedback">
                    <div class="col-sm-2">
                      <label class="control-label">País</label>
                    </div>
                    <div class="col-sm-9">
                        <?
                        $array_pais = array('Selecione...', 'Alemanha', 'Angola', 'Argentina', 'Bolívia', 'Brasil', 'Camarões', 'Canadá', 'Chile', 'China', 'Colombia',
                            'Costa Rica', 'Cuba', 'Dinamarca', 'Equador', 'Espanha', 'Estados Unidos', 'França', 'Holanda', 'Inglaterra', 'Itália', 'Japão',
                            'México', 'Nigéria', 'Panamá', 'Paraguai', 'Peru', 'Porto Rico', 'Portugal', 'Rússia', 'Senegal', 'Taiwan', 'Uruguai', 'Venezuela'
                        );
                        echo '<select class="form-control" name="pais" id="pais">';
                        foreach ($array_pais as $valor) {
                            echo '<option>' . $valor . '</option>';
                        }
                        echo '</select>';
                        ?>
                    </div>
                  </div>
                  <div class="form-group has-feedback">
                    <div class="col-sm-2">
                      <label class="control-label">Nome:</label>
                    </div>
                    <div class="col-sm-10">
                      <input id="nome" name="nome" class="form-control" type="text" placeholder="Digite o nome">
                    </div>
                  </div>
                  <div class="form-group has-feedback">
                    <div class="col-sm-2">
                        <label class="control-label">Empresa</label>
                    </div>
                    <div class="col-sm-10">                 
                        <input id="empresa" name="empresa" class="form-control" type="text" placeholder="Digite a empresa">
                    </div>
                  </div>
                  <div class="form-group">
                    <div class="col-sm-12 col-sm-offset">

                        <div style="float:left; padding-right:30px">
                            <button type="submit" class="btn btn-lg btn-primary" aria-label="Left Align">
                                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>&nbsp; Adicionar
                            </button>
                        </div>

                        <div style="float:right;">
                            <button class="btn btn-lg btn-warning" onClick="parent.location='exibir.php'">
                        </div>                  
                    </div>  
                  </div>
                </div>

              </form>
            </div>
          </div>
          <div class="col-md-2"></div>
        </div>
      </div>
    </div>
    <div class="section">
      <div class="container">
        <div class="row">
          <div class="col-md-12">
            <div class="jumbotron">
              <table data-toggle="table" data-cache="false" class="table" id="list">
                <thead align="center">
                  <tr bgcolor="#FFFFFF">
                    <th>PAÍS</th>
                    <th>NOME</th>
                    <th>EMPRESA</th>
                    <th>AÇÕES</th>
                  </tr>
                </thead>
                <tbody></tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>


    <div class="modal fade" id="inserir_modal" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h3 class="modal-title">
                    <span class="glyphicon glyphicon-file"></span>&nbsp; Inserir
                    </h3>
                </div>
                <div class="modal-body"></div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
                </div>
            </div>
        </div>
    </div>


    <div class="modal fade" id="editar_modal" role="dialog">
        <div class="modal-dialog">
            <form id="edit_form" class="form">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h3 class="modal-title">
                        <span class="glyphicon glyphicon-pencil"></span>&nbsp; Editar
                        </h3>               
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label class="control-label">País:</label>
                            <input id="pais_input" name="nome" class="form-control" type="text" placeholder="Digite o pais">
                        </div>          
                        <div class="form-group">
                            <label class="control-label">Nome:</label>
                            <input id="nome_input" name="nome" class="form-control" type="text" placeholder="Digite a empresa">
                        </div>
                        <div class="form-group">
                            <label class="control-label">Empresa:</label>
                            <input id="empresa_input" name="empresa" class="form-control" type="text" placeholder="Digite a empresa">
                        </div>
                        <input id="id_input" type="hidden" name="id">
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-success" aria-label="Left Align">
                            <span class="glyphicon glyphicon-floppy-disk" aria-hidden="true"></span>&nbsp; Gravar
                        </button>

                        <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>

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


    <div class="modal fade" id="deletar_modal" role="dialog">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h3 class="modal-title">
                    <span class="glyphicon glyphicon-trash"></span>&nbsp; Exclusão
                    </h3>
                </div>
                <div class="modal-body"></div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
                </div>
            </div>
        </div>
    </div>  



<script>

    function update_list() {
        $.getJSON("get_list.php", function (data) {
            if (data.response) {
                $("#list").find("tbody").empty();
                data.results.forEach(function (i) {
                    $("#list").find("tbody").append(
                        "<tr>" +
                        "<td>" + i.pais + "</td>" +
                        "<td>" + i.nome + "</td>" +
                        "<td>" + i.empresa + "</td>" +
                        "<td align='center'><a class='btn btn-primary glyphicon glyphicon-pencil' title='Editar' id='edit_link' href='" + JSON.stringify(i) + "'></a> | <a class='btn btn-danger glyphicon glyphicon-trash' title='Deletar' id='delete_link' href='"  + JSON.stringify(i) + "'></a></td>" +
                        "</tr>"
                    );
                });
            }
        });
    }

    $("#list").delegate('#edit_link', 'click', function (e) {
        e.preventDefault();
        var info = JSON.parse($(this).attr("href"));
        var $modal = $("#editar_modal");
        $modal.find("#pais_input").val(info.pais);
        $modal.find("#nome_input").val(info.nome);
        $modal.find("#empresa_input").val(info.empresa);
        $modal.find("#id_input").val(info.id);
        $modal.modal('show');
    });

    update_list();
    $('#submit_form').submit(function () {
        $.ajax({
            url: "inserir.php",
            type: "POST",
            data: $(this).serialize(),
            dataType: "json",
            success: function (data) {
                if (data.response) {
                  var $modal = $('#inserir_modal');
                  $modal.find(".modal-body").html(data.message);
                  $modal.modal('show');
                  update_list();
                } else {
                  alert(data.message);
                }
            }
        });
        return false;
    });

    $('#edit_form').submit(function () {
        $.ajax({
            url: "editar.php",
            type: "POST",
            data: $(this).serialize(),
            dataType: "json",
            success: function (data) {
                if (data.response) {
                    var $modal = $('#inserir_modal');
                    $("#editar_modal").modal('hide');
                    $modal.find(".modal-body").html(data.message);
                    $modal.modal('show');
                    update_list();
                } else {
                    alert(data.message);
                }
            }
        });
        return false;
    }); 

</script>

edit.php

<?php
require('conexao.php');

    $id = $_POST['id'];
    $pais = $_POST['pais'];
    $nome = $_POST['nome'];
    $empresa = $_POST['empresa'];

    $query = "UPDATE tb_visitas SET nome = '$nome', empresa = '$empresa', pais= '$pais' WHERE id = $id ";
    $update = mysql_query($query);

        if ($update) {
            $res['response'] = true;
            $res['message'] = "Registro atualizado com sucesso!";
        } else {
            $res['response'] = false;
            $res['message'] = "Erro: " . $query . "<br>" . mysql_error();
        }

    echo json_encode($res);

    ?>

get_list.php

<?php

require('conexao.php');

    $sql = "SELECT id, pais, nome, empresa FROM tb_visitas";

    $table = mysql_query($sql) or die(mysql_error());

    if (mysql_num_rows($table) > 0) {
        $res['response'] = true;
        while($row = mysql_fetch_assoc($table)) {
            $res['results'][] = $row;
        }
    } else {
        $res['response'] = false;
        $res['message'] = "Erro: " . $sql . "<br>" . mysql_error($con);
    }

    echo json_encode($res);

    ?>

deletar.php

<?php

require('conexao.php');

$id = $_POST['id'];

$query = "DELETE FROM tb_visitas WHERE id = $id ";

if (mysql_query($query)) {
    $res['response'] = true;
    $res['message'] = "Registro deletado com sucesso!";
} else {
    $res['response'] = false;
    $res['message'] = "Erro: " . $query . "<br>" . mysql_error($con);
}

echo json_encode($res);

?>

conexao.php

<?php

error_reporting(E_ALL ^ E_DEPRECATED);

$hostname = 'localhost';
$username = 'root';
$senha = '';
$banco = 'visitas';

$db = mysql_connect($hostname, $username, $senha); 
mysql_set_charset('latin1',$db);
mysql_select_db($banco, $db) or die ("Não foi possível conectar ao banco MySQL");

?>

所以,现在我想在每个项目中放置一个复选框,以便能够选择多个记录并立即删除它们。另一个问题是,当我编辑一个记录时,如果我把文本放在它填满的字段中,但如果我选择它就不起作用。我们的想法是,选择字段包含所有国家/地区的选项,并允许已选择的记录中的该项目。我希望你明白我的需要。感谢。

1 个答案:

答案 0 :(得分:0)

据我所知,你有两个问题:

  1. 如何在CRUD列表中放置复选框,以便一次删除所有项目。

    您似乎正在使用update_list()加载表格中的所有项目。既然如此,您需要使用复选框元素在该行中添加额外的<td>

            data.results.forEach(function (i) {
                $("#list").find("tbody").append(
                    "<tr>" +
                    "<td><input class='item_checkbox' type='checkbox'/></td>" +
                    "<td>" + i.pais + "</td>" +
                    "<td>" + i.nome + "</td>" +
                    "<td>" + i.empresa + "</td>" +
                    "<td align='center'><a class='btn btn-primary glyphicon glyphicon-pencil' title='Editar' id='edit_link' href='" + JSON.stringify(i) + "'></a> | <a class='btn btn-danger glyphicon glyphicon-trash' title='Deletar' id='delete_link' href='"  + JSON.stringify(i) + "'></a></td>" +
                    "</tr>"
                );
            });
    

    一旦你有了这个集合,你就可以使用jquery按类.item_checkbox收集所有复选框并运行删除功能。

  2. 如何确保在编辑项目时预先选择了SELECT国家/地区字段

    由于您正在使用自举模式,因此在编辑项目时,将弹出显示该信息的模态。您需要做的是将该项目的国家/地区ID发送到该模式的表单以便可以预先选择,因此请执行以下更改:

    首先在#editar_modal

    <div class="form-group">
        <label class="control-label">País:</label>
        <select id="pais_input" name="pais">
        <?php foreach ($array_pais as $pais) { ?>
            <option value="<?php echo $pais ?>"><?php echo $pais ?></option>
        <?php } ?>  
    </div>
    

    然后在'#edit_link', 'click', function (e)添加:

    $modal.find("#pais_input").val(info.pais);