Save to database using jquery

1

I need to get the data typed in my modal window and set it in the database. Below are the pages.

listUser.php

<div class = "conteudo">
                <div class="container-fluid">
                    <div align="left" id="inserir">
                        <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">
                            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Inserir
                        </button>
                    </div>

                                <!-- Listar cargos -->
                <legend>Relação de Cargos</legend>
                <?php include "listaUsuario2.php";?>

                </div>
                <!-- Fim listar cargos -->

</div> <!-- FECHA CONTEUDO -->




<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Novo Úsuario</h4>
      </div>
    <div class="modal-body">            
        <div align="center">
            <form class="form-horizontal" action="salvarUsuario.php" method="post" id="cadUsuario">
            <fieldset>

            <!-- Text input-->
            <div class="control-group">
              <label class="control-label" for="TXT_NOMEX_USUAR"></label>
              <div class="controls">
                <input id="TXT_NOMEX_USUAR" name="TXT_NOMEX_USUAR" type="text" placeholder="Nome" class="input-large">

              </div>
            </div>

            <!-- Text input-->
            <div class="control-group">
              <label class="control-label" for="TXT_ENDER_EMAIL"></label>
              <div class="controls">
                <input id="TXT_ENDER_EMAIL" name="TXT_ENDER_EMAIL" type="text" placeholder="Email" class="input-xlarge">

              </div>
            </div>

            <!-- Password input-->
            <div class="control-group">
              <label class="control-label" for="TXT_SENHA_USUAR"></label>
              <div class="controls">
                <input id="TXT_SENHA_USUAR" name="TXT_SENHA_USUAR" type="password" placeholder="Senha" class="input-small">

              </div>
            </div>            
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
        <button type="button" class="btn btn-primary" onclick="$('#cadUsuario').submit()">Salvar</button>
      </div>
    </div>
  </div>
</div>

saveUsername.php

<?php
    // incluindo o arquivo que faz a conexao com o banco
    include ("../includes/conexao.php");

    $nome = isset($_POST['TXT_NOMEX_USUAR']) ? $_POST['TXT_NOMEX_USUAR'] : '';
    $email = isset($_POST['TXT_ENDER_EMAIL']) ? $_POST['TXT_ENDER_EMAIL'] : '';
    $senha = isset($_POST['TXT_SENHA_USUAR']) ? $_POST['TXT_SENHA_USUAR'] : '';


    $query = "INSERT INTO tbl_USUARIOS (TXT_NOMEX_USUAR, TXT_ENDER_EMAIL, TXT_SENHA_USUAR) VALUES";
    $query .=  "('$nome','$email','$senha')";

    //executando a query
    $inserir = mysql_query($query)
    or die(error());

    $response = array("success" => true);

    //fechando a conexao com o banco
    mysql_close($conn);

?>

The error that is giving is that when I click save nothing appears, the page stays the same way. What I'm doing wrong.

---------------------------------- x I'm saving, but when I do ajax, I can not make it work at all. I will put the code to see where it is wrong.

userlist.php

<script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery('#cadUsuario').submit(function(){
            var dados = jQuery( this ).serialize();

            jQuery.ajax({
                type: "POST",
                url: "salvarUsuario.php",
                data: null,
                success: function( data )
                {
                    alert( data );
                }
            });

            return false;
        });
    });
</script>
<form class="form-horizontal" action="" method="post" id="cadUsuario">
            <fieldset>

            <!-- Text input-->
            <div class="control-group">
              <label class="control-label" for="TXT_NOMEX_USUAR"></label>
              <div class="controls">
                <input id="TXT_NOMEX_USUAR" name="TXT_NOMEX_USUAR" type="text" placeholder="Nome" class="input-large">

              </div>
            </div>

            <!-- Text input-->
            <div class="control-group">
              <label class="control-label" for="TXT_ENDER_EMAIL"></label>
              <div class="controls">
                <input id="TXT_ENDER_EMAIL" name="TXT_ENDER_EMAIL" type="text" placeholder="Email" class="input-xlarge">

              </div>
            </div>

            <!-- Password input-->
            <div class="control-group">
              <label class="control-label" for="TXT_SENHA_USUAR"></label>
              <div class="controls">
                <input id="TXT_SENHA_USUAR" name="TXT_SENHA_USUAR" type="password" placeholder="Senha" class="input-small"> 
              </div>
            </div>
            <br>
            <br>          
    </div>
        <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
        <button type="submit" class="btn btn-primary" id="botao_cadUsuario">Salvar</button>

And the new page to actually do the registration is like this.

saveUsername.php

<?php
    // incluindo o arquivo que faz a conexao com o banco
    include ("../includes/conexao.php");

    $nome = isset($_POST['TXT_NOMEX_USUAR']) ? $_POST['TXT_NOMEX_USUAR'] : '';
    $email = isset($_POST['TXT_ENDER_EMAIL']) ? $_POST['TXT_ENDER_EMAIL'] : '';
    $senha = isset($_POST['TXT_SENHA_USUAR']) ? $_POST['TXT_SENHA_USUAR'] : '';


    $query = "INSERT INTO tbl_USUARIOS (TXT_NOMEX_USUAR, TXT_ENDER_EMAIL, TXT_SENHA_USUAR) VALUES";
    $query .=  "('$nome','$email','$senha')";

    //executando a query
    $inserir = mysql_query($query)
    or die(error());

    $response = array("success" => true);

    //fechando a conexao com o banco
    mysql_close($conn);

    echo "Cadastrado com Sucesso!";

?>

It is not a problem in sql because it works perfectly, the business is that when I click the save button it does not recognize that button is saving.

    
asked by anonymous 01.06.2015 / 21:49

2 answers

2

You're mixing things up. JQuery should not be never placed in inline HTML, just like Vanilla JS, this is a horrible practice that should be avoided to the utmost. You need to do a handle in the click event of the button by a separate JavaScript file, like this:

$(document).ready(function() {
    $('button.btn.btn-primary').click(function() {
        $('#cadUsuario').submit();
    });
});

I recommend that you add a handle to the button that will submit on the form, so the query is less generic and you do not run the risk of another similar button activating the event . Staying like this:

$(document).ready(function() {
    $('#botao_submit').click(function() {
        $('#cadUsuario').submit();
    });
});

To make the request automatically without the need for the page to be redirected / updated, it is necessary to use the AJAX instead of the submit() in the form. The code below is very simple but works correctly, you can adapt it according to your needs:

$(document).ready(function() {
    $('button.btn.btn-primary').click(function() {
        $.ajax({
          type: "POST",
          url: "salvarUsuario.php",
          data: null,
          success: function(data) {
            // Coloque aqui as instruções para fechar o dialog
          },
          error: function(request, status, error) {
            // Aqui você trata um erro que possa vir a ocorrer
            // Exemplo:
            alert("Erro: " + request.responseText);
          }
        });
    });
});

As I told you, recommend taking a look at here to better understand how AJAX it works.

    
01.06.2015 / 22:04
1

At first, debug the code to see if the form is going correctly.

<?php // incluindo o arquivo que faz a conexao com o banco
    include ("../includes/conexao.php");
    if (!empty($_POST)) {
    var_dump('entrou no post'); // se passar daqui já é uma boa notícia.
    die();
    //se passar daqui, apague o var_dump e die acima.
        $nome = isset($_POST['TXT_NOMEX_USUAR']) ? $_POST['TXT_NOMEX_USUAR'] : '';
        $email = isset($_POST['TXT_ENDER_EMAIL']) ? $_POST['TXT_ENDER_EMAIL'] : '';
        $senha = isset($_POST['TXT_SENHA_USUAR']) ? $_POST['TXT_SENHA_USUAR'] : '';


        $query = "INSERT INTO tbl_USUARIOS (TXT_NOMEX_USUAR, TXT_ENDER_EMAIL, TXT_SENHA_USUAR) VALUES";
        $query .=  "('$nome','$email','$senha')";

        //executando a query
        $inserir = mysql_query($query)
        or die(error());
        //var_dum($inserir); //debuga seu SQL

        $response = array("success" => true);

        //fechando a conexao com o banco
        mysql_close($conn);
    }
?>
    
01.06.2015 / 23:04