-2

I have this index.php code:

<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);

?>

and 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");

?>

So, now I'd like to put a checkbox in each item for being able to select several records and delete them at once. Another question, when I edit a record if I put a text the field it's filled, but if I put a select it doesn't work. The idea is the select field has all options of countries and letting that item from the record already selected. I hope you understand what I need. Thanks.

4
  • It's better to ask one objective question at a time... say what is working and show where you got stuck Sep 25, 2015 at 13:55
  • Actually whole that code is working, I wanna just improve it, with these questions. Thks
    – Neto
    Sep 25, 2015 at 13:59
  • 1
    We understood what you need. Now it's time for you to understand what to ask and what not to ask here in StackOverflow, and how to proceed after taking the tour. Good luck!
    – al'ein
    Sep 25, 2015 at 14:05
  • To get better quality answers, you need to do some research, attempt yourself, then return if you get stuck or have a specific question.
    – Marc L.
    Sep 25, 2015 at 14:06

1 Answer 1

0

From what I understand, you have two questions:

  1. How to put checkboxes on your CRUD list in order to delete all items at once.

    It seems that you are using update_list() to load all items on your table. Since thats the case, you need to add an extra <td> in that row to that iteration with the checkbox element.

            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>"
                );
            });
    

    Once you have that set, you can then use jquery to collect all checkboxes by class .item_checkbox and run a delete function.

  2. How to make sure the SELECT country field is pre-selected when you EDIT an item

    Since you are using bootstrap modals, when you edit an item, that modal will popup showing that info. What you need to do is send that item's country ID to that modal's form so that it can be preselected, so do the following change:

    first in #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>
    

    then in '#edit_link', 'click', function (e) add:

    $modal.find("#pais_input").val(info.pais);
    
6
  • Hi...the Select worked perfectly. And Delete I've tried some like that: $(this).click(function() { var id = $('.item_checkbox:checkbox:checked').map(function(){ return this.id; }).get(); alert(id); }); and I've put it "<td><input class='item_checkbox' id='" + i.id + "' type='checkbox'/></td>" + It creates an array but I'm not getting to send with ajax and delete the records. Damn it.
    – Neto
    Sep 25, 2015 at 22:56
  • could help me again? Thks
    – Neto
    Sep 26, 2015 at 14:14
  • I made work. ´<? require("conexao.php"); if($_REQUEST['delete']) { $totalarray = sizeof($del); for($i=0; $i<$totalarray; $i++) { if(!empty($del[$i])){ mysql_query("DELETE FROM tb_visitas WHERE id=".$del[$i]) or die(mysql_error()); } } $msg="Values Deleted Successfully";} ?>´ function CheckAll() { for (var i=0; i<document.frmDelSelected.elements.length; i++) { var e = document.frmDelSelected.elements[i]; if (e.name != "allBoxes") e.checked = document.frmDelSelected.allBoxes.checked; } } I wanted to make the way you did, using ajax, but it didn't work for me. =(
    – Neto
    Sep 28, 2015 at 16:06
  • you are using the jquery library, therefore it would be better for you to use its functions.. You are using document.frmSelectedthan iterating, where with jquery all you would need to do is apply events to all by class name.. wanna do a Teamviewer session?
    – CodeGodie
    Sep 28, 2015 at 16:12
  • For me, great...929 238 508 - 6299
    – Neto
    Sep 28, 2015 at 16:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.