Save to database using jquery

Asked

Viewed 2,331 times

1

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

listarUsuario.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>

salvarUsuario.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 on save nothing appears, the page is the same way. What I am doing wrong.

----------------------------------x I’m able to save, but when I do it by ajax, I can’t make it work at all. I will put the code to see where esotu erring.

listUsuario.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 register is like this.

salvarUsuario.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 no problem in sql as it is working perfectly, the business is that when I click the save button it does not recognize that that button is save.

2 answers

2


You’re mixing things up. The jQuery shouldn’t be never placed in inline HTML, just like Vanilla JS, this is a horrible practice that should be avoided to the maximum. You need to make a Handle in the button click event by a separate Javascript file, thus:

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

I recommend adding an identifier to the button that will give Submit on the form, so as to query is less generic and you do not run the risk of another similar button activating the event. Thus:

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

To make the request automatically without the page being redirected/updated, it is necessary to use AJAX instead of 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 here to better understand how AJAX works.

  • if I just change this will already work ?

  • I did it this way but it didn’t work.

  • Apparently yes. Values will be entered in the database correctly if your connection file is valid. I only warn you that you have not programmed any means of response, so this will not happen.

  • You have jQuery inserted into your page? What didn’t work? Without information there’s no way anyone can help you.

  • It registers in the database, only that the page does not give a refresh, it goes to the page save Your.php and is static, I need it to go back to the page where it was put with the closed modal.

  • Oh yes, you will have to work with AJAX to be able to perform this type of action without leaving or giving refresh on the page.

  • Do you have any tips, topics or videos, where I can learn more about this ? I’m having a lot of difficulty in this area and I need something to enrich my knowledge, have something to indicate ?

  • There are several articles on the internet. By the way, I did a very basic article about this: http://blog.rafaelalmeidatk.com/creatindo-requisicoes-ajax-com-jquery/ I will edit this answer with more information as soon as possible, I am leaving now.

  • take one more look please.

  • @Renanrodrigues sorry for the delay, I was only available now. Take a look again at the answer and see if you understand.

Show 5 more comments

1

Start by debugging 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);
    }
?>

Browser other questions tagged

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