Insert Modal data into table via Ajax PHP and Javascript

Asked

Viewed 458 times

1

I’m trying to insert data from a table of my Modal in the table "father" of my page, basically I have a modal, where I gave a select to bring the data that is not in the parent table and the user enter this data, what happens is that the requests are made correctly, however the data in the parent table the value returns "null", here my html page:

<div class="container-fluid">
        <table class="table table-bordered table-striped table-condensed" id="tablePrincipal">
            <thead>
                <tr>
                    <th colspan="4">Papéis funcionais do usuário
                        <button class="fa fa-trash" aria-hidden="true" name="Delete" value="Delete" id="deletar" ></button>
                        <button class="fa fa-plus" aria-hidden="true" data-toggle="modal" data-target="#Modal"></button>
                    </th><br>
                </tr>

                <tr>
                    <a style="cursor: pointer;"><td><input type='checkbox' id="checkTodos__" /><b>  Identificador</b><span class="gridSortAsc"></span></td></a>
                    <td><b>Nome</b><span class="gridSortAsc"></span></td>
                </tr>
            </thead>
            <?php
                $SQL = "SELECT ADR.IDROLE, ADR.NMROLE, ADR.CDROLE FROM ADUSERROLE ADUR, ADROLE ADR WHERE ADUR.CDROLE = ADR.CDROLE AND ADUR.CDUSER = '".$cduser."'";

                $SQL.=" ORDER BY ADR.IDROLE, ADR.NMROLE";

                $cur = $conn->execute($SQL);

                if($cur){
                    while(!$cur->EOF){
                        $linha = "<tbody><tr>";
                        $linha.= "<td> <input type='checkbox' />&nbsp;&nbsp;".$cur->fields['idrole']."</td>";
                        $linha.= "<td>".$cur->fields['nmrole']."</td>";
                        $linha.= "</tr></tbody>";
                        echo $linha;
                        $cur->MoveNext();

                        $cdrole = $cur->fields["cdrole"];
                    }
                }
            ?>
        </table>
    </div>  

    <!-- Modal para exibição dos dados para adicionar na tabela pai -->
    <div class="modal fade" id="Modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Insira um novo registro</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">x</span>
                    </button>
                </div>

                <form id="formulario">
                    <div class="modal-body">
                        <button class="fa fa-search" id="pesquisarDados" onclick="mostrarTabela();"></button>       
                        <label for="pesquisa">Pesquisar</label>
                        <input type="text" name="pesquisar" id="pesquisar" class="form-control" aria-describedby="pesquisa" placeholder="Pesquisar">    
                        <table style="display: none;" class="table table-bordered table-striped table-condensed table-hover" id="mostraTable">
                            <thead>
                                <tr>
                                    <a style="cursor: pointer;"><td><input type='checkbox' value="1" id="inputDado" name="inputDado" /><b>  Identificador</b><span class="gridSortAsc"></span></td></a>
                                    <td><b>Nome</b><span class="gridSortAsc"></span></td>
                                </tr>
                            </thead>    
                            <tbody id="mostraDadosTable">

                            </tbody>
                        </table>
                    </div>      
                </form>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
                    <button type="button" class="btn btn-primary" id="inserirDado" onclick="insereDado();">Salvar</button>
                </div>
            </div>
        </div>
    </div>

That form is inside my Modal. And here my Javascript with Ajax, which makes the request to my PHP page where I have the INSERT in the database:

<script>
        //seleciona os checkbox
        $("#checkTodos__").change(function () {
            $("input:checkbox").prop('checked', $(this).prop("checked"));
        });

        $("#checkTodos__").click(function(){
            $('input:checkbox').not(this).prop('checked', this.checked);
        });

        $("#inputDado").change(function () {
            $("input:checkbox").prop('checked', $(this).prop("checked"));
        });

        $("#inputDado").click(function(){
            $('input:checkbox').not(this).prop('checked', this.checked);
        });

        var checkTodos = $("#checkTodos");
        checkTodos.click(function () {
            if ($(this).is(':checked')){
                $('input:checkbox').prop("checked", true);
            } else {
                $('input:checkbox').prop("checked", false);
            }
        });

        //limpa o campo de pesquisa do modal
        $('#Modal').on('hidden.bs.modal', function () {
            $('#formulario').each(function() {
                $('#pesquisar').val(''); 
            });
        });

        //mostra a tabela no modal quando clica no Pesquisar
        function mostrarTabela(){
            document.getElementById('mostraTable').style.display = '';
        }

        //quando não tiver algo digitado na pesquisa, irá trazer todos os registros
        function pesquisaTodosDados(){
            $('#mostraDadosTable').empty(); //Limpando a tabela
            $('#formulario').on('submit', function(e){
                e.preventDefault();
                $.ajax({
                    type:'POST',
                    dataType: 'json',   
                    url: 'actions.php',
                    data: { 
                        selecionaDados: "true",
                        iduser: '1185621'
                    },
                    success: function(data){
                        //alert('sucesso');
                        for(var i = 0; data.length > i; i++){
                            //Adicionando registros retornados na tabela
                            $('#mostraDadosTable').append('<tr><td><input type="checkbox" value="1" id="inputDado" name="inputDado" />&nbsp;&nbsp;'+data[i].idrole+'</td><td>'+data[i].nmrole+'</td></tr>');
                        }
                    }
                });
            });
        }

        //requisição assíncrona via Ajax e método Post para o arquivo getDados, e trás o que o usuário digitou na pesquisa
        function pesquisaDadosFiltrados(){
            $('#mostraDadosTable').empty(); //Limpando a tabela
            $('#formulario').on('submit', function(e){
                e.preventDefault();
                $.ajax({
                    type:'POST',
                    dataType: 'json',
                    url: 'getDados.php?pesquisar',
                    data: {
                        pesquisar: $('#pesquisar').val()
                    },
                    success: function(data){
                        //Adicionando os registros filtrados na tabela
                        for(var i = 0; data.length > i; i++){
                            $('#mostraDadosTable').append('<tr><td><input type="checkbox" value="1" id="inputDado" name="inputDado" />&nbsp;&nbsp;' + data[i].idrole + '</td><td>' + data[i].nmrole + '</td></tr>', '');
                        };
                    },
                    error: function() {
                        alert('Ocorreu um erro na requisição');
                    }
                });
            });
        }

        //dispara as funções para pesquisar todos os dados ou somente os dados filtrados, conforme requisição
        $(document).ready(function(){

            $('#pesquisarDados').click(function(){
                pesquisa = $('#pesquisar').val()
                pesquisarDados(pesquisa);
            });

            function pesquisarDados(pesquisa){
                if (pesquisa == "") {
                    pesquisaTodosDados();
                } else {
                    pesquisaDadosFiltrados();
                }
            }
        });

        //insere dados conforme requisição for disparada no botão salvar do modal, ESSA FUNÇÃO É A QUE ESTOU COM PROBLEMAS, AO INSERIR OS DADOS RETORNADOS DA REQUISIÇÃO NA TABELA "PAI"

        function insereDado(){
            $(document).ready(function(){
                var arr = [];            
                $("input:checkbox[name=inputDado]:checked").each(function(){
                    arr.push($(this).val());
                    console.log('valor checkbox inputDado: ', arr);
                });

                $.ajax({
                    type:'POST',
                    dataType: 'json',
                    url: 'insertDado.php',
                    data: {
                        insereDados : "true",
                        inputDado : arr
                    },
                    success: function(data){
                        console.log('dado retornado: ', data);
                        console.log('valor checkbox inputDado no success: ', inputDado);
                        for(var i = 0; data.length > i; i++){
                            $('#tablePrincipal').append('<tr><td>' + data[i].idrole + '</td><td>' + data[i].nmrole + '</td></tr>');  
                        };
                    },
                    error: function() {
                        alert('Ocorreu um erro na requisição');
                    }
                });
            });
        }
    </script>

and finally, my page insertDado.php that makes the INSERT in the table

<?php
require_once("../../global.php");
require_once("../specific/se_schulze.php");

$inputDado = $_POST['inputDado'];

function insereDados($inputDado){

    global $conn;

    $SQL = " INSERT INTO ADROLE (idrole, nmrole) VALUES ( '" . $inputDado . "', '" . $inputDado . "')";

    $cur = $conn->execute($SQL);

    $vetor = "";
    $registro = "";

    if($cur){  
        $registro["idrole"] = $cur->fields["idrole"];
        $registro["nmrole"] = $cur->fields["nmrole"];
        $vetor[] = $registro;
    }

    echo json_encode($vetor);
}

insereDados($inputDado);

?>

I get my "inputDado" by parameter but I think that’s where the error is. Can anyone help me? I’m already 1 day into this problem and I can’t fix it

inserir a descrição da imagem aqui

  • 1

    To avoid long discussions in the comments; your conversation was moved to the chat and you can continue there (by system recommendation, more than twenty comments followed in the post) - About the question itself, there is a lot of code that you can not test or reproduce, want to reduce the functionality to a [mcve] so that we can help. Capable until with EMCV you locate the code problem before us.

  • 1

    is the link of the first comment --> https://chat.stackexchange.com/rooms/85583/discussion-on-questionby-bruno-elias-de-souza-inserir-dados-do-modal-na-tabela - but moving in the same chat does not work, you have to go in and write there (the author receives notification)

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.