I wanted to show an Alert after a form has been sent, PHP, JAVASCRIPT, HTML, AJAX

Asked

Viewed 933 times

2

I’m in trouble, where my form is being sent to the bank but in Alert appears alert("erro ao enviar formulário");.

    <?php 

if(!empty($_FILES['uploaded_file'])){
    $username = 'root';
    $password = '';
    $connection = new PDO( 'mysql:host=localhost;dbname=nise', $username );



    $query = "INSERT INTO denuncia (descricao, imagem, id_usuario, qual_descricao,id_bloco, id_denuncia_oque) 
          VALUES (:descricao, :imagem, :id_usuario, :qual_descricao, :id_bloco, :id_denuncia_oque)";



    $statement = $connection->prepare($query);





    $path = "img_denuncia/";
    $path = $path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path))



    $valores = array();
    $valores[':descricao'] = $_POST['descricao_denuncia'];
    $valores[':imagem'] = $_FILES['uploaded_file']['name'];
    $valores[':id_usuario'] = 2;
    $valores[':qual_descricao'] = $_POST['qual_descricao'];
    $valores[':id_bloco'] = $_POST['bloco_denuncia'];
    $valores[':id_denuncia_oque'] = $_POST['id_denuncia_oque'];



    if( $result = $statement->execute($valores))
        {
         echo 1; // dados enviados com sucesso
        }
        else
        {
        // na verdade o else não é necessário mas se preferir pode colocar
         echo 0; // erro ao tentar enviar dados 
        }




}
?>

Here is the ajax

     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
    // evento de "submit"
    $("#b_enviar").click(function (e) {
        // parar o envio para que possamos faze-lo manualmente.
        e.preventDefault();
        // captura o formulário
        var form = $('#caixa')[0];
        // cria um FormData {Object}
        var data = new FormData(form);
        // processar
        $.ajax({
            type: "POST",
            url: "http://localhost/nise/aluno.php", //acerte o caminho para seu script php
            data: data,
            processData: false, // impedir que o jQuery tranforma a "data" em querystring
            contentType: false, // desabilitar o cabeçalho "Content-Type"
            //cache: false, // desabilitar o "cache"
            // manipular o sucesso da requisição
        }).done(function(retorno){
              if(retorno==1)
              {
                alert("Formulário enviado com sucesso");
              }
               else
              {
                alert("erro ao enviar formulário");

              }
        });
    });
});
</script>

Here is my form

 <!--Caixa de texto-->
  <form id="caixa" class="center-block row col-xl-6" enctype="multipart/form-data" name="formulario"  method="POST" action="aluno.php">
    <br>
      <div class="row p-0 no-margin col-12 col-sm-12  col-md-12 col-lg-10 col-xl-12" >
        <div class="form-group">
          <label for="sel1">Bloco:</label>
          <select class="form-control " name="bloco_denuncia" id="bloco" required="required" placeholder="ex: Bloco 3" >
            <option value="" disabled selected>Ex: Computação</option>
            <option value="1">Bloco - Computação</option>
            <option value="2">Bloco - Mecânica</option>
            <option value="3">Bloco - Química</option>
            <option value="4">Bloco - Administrativo</option>
            <option value="5">Biblioteca </option>
            <option value="6">Ginásio </option>
            <option value="7">Auditório</option>
            <option value="0">Outros</option>
          </select>
          </div>
      <div class="form-group">
          <label for="sel1">O que:</label>
          <select select="required" class="form-control" name="id_denuncia_oque" id="sel1" required="required" >
            <option value="" disabled selected>Ex: Laboratório</option>
            <option value="1">Sala</option>
            <option value="2">Banheiro(Térreo)</option>
            <option value="3">Banheiro(Superior)</option>
            <option value="4">Laboratório</option>
            <option value="5">Coordenação</option>
            <option value="6">Gabinete</option>
            <option value="7">Telecom</option>
            <option value="8">Outros</option>

          </select>
          </div>

            <div class="form-group">
              <label for="usr">Qual:</label>
              <input type="text" class="form-control" id="usr" name="qual_descricao" placeholder="ex: ar-condicionado " required="required" >
            </div>

      </div>
       <textarea  id="form-control"class="noresize  col-12 col-sm-12 mb-12 col-md-12 col-lg-10 col-xl-12 " name="descricao_denuncia" placeholder="Faça sua denúncia aqui... " id="denuncia" rows="13" required="required" autofocus="autofocus">
       </textarea>

       <br>
       <div class="row p-0 no-margin col-12 col-sm-12  col-md-12 col-lg-10 col-xl-12">  
            <div class="botao p-0 no-margin col-6 col-sm-6 mb-3 col-md-6 col-lg-2 col-xl-10">
           <label class="file-upload btn btn-primary">
                Escolha o arquivo... <input  type="file" name="uploaded_file"/ accept="image/*">
            </label>  
           <small class="form-text text-muted">As suas mensagens não serão totalmente anônimas.</small>
            </div>
          <div class="botao p-0 no-margin col-6 col-sm-6 mb-3 col-md-6 col-lg-10 col-xl-2 text-right ">
               <input id="b_enviar" type="submit" class="btn btn-success" value="Enviar" name="enviar"/>
          </div>
      </div>
    </form>
    <br>
    <!--Fim da caixa-->

If you have javascript solution you can send it

  • tried to use print in place of echo?

  • Yeah, it’s not right.

2 answers

3


If you want to submit all (possible) form fields, with ajax, just use: new FormData()

replace your script with:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
    // evento de "submit"
    $("#b_enviar").click(function (e) {
        // parar o envio para que possamos faze-lo manualmente.
        e.preventDefault();
        // captura o formulário
        var form = $('#caixa')[0];
        // cria um FormData {Object}
        var data = new FormData(form);
        // processar
        $.ajax({
            type: "POST",
            url: "aluno.php", //acerte o caminho para seu script php
            data: data,
            processData: false, // impedir que o jQuery tranforma a "data" em querystring
            contentType: false, // desabilitar o cabeçalho "Content-Type"
            //cache: false, // desabilitar o "cache"
            // manipular o sucesso da requisição
        }).done(function(retorno){
              if(retorno==1)
              {
                //alert("Formulário enviado com sucesso");
                $("#myModalSucess").modal('show');
              }
               else
              {
                //alert("erro ao enviar formulário");
                $("#myModalError").modal('show');

              }
        });
    });
});
</script>

To use modal instead of Alert

1 - Use the libraries

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

2 - In the script replace the Alerts with the lines that invoke the modals (see the above script)

3 - Paste the following code preferably before closing tag </body>

4 - To learn more about modal click here

<!-- Modal HTML Erro -->
<div id="myModalError" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Erro</h4>
            </div>
            <div class="modal-body">
                <p class="text-warning"><small>erro ao enviar formulário </small></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger waves-effect waves-light" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

 <!-- Modal HTML Sucesso -->
<div id="myModalSucess" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Sucesso </h4>
            </div>
            <div class="modal-body">
                <p>Tarefas realizadas com sucesso. </p>
                <p class="text-warning"><small>Formulário enviado com sucesso</small></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-success waves-effect waves-light" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div> 

BONUS:

so that the placeholder from the working textarea you must remove the spaces, line break etc...from within the textarea

see how it is (closing tag on the bottom line)

   <textarea  ....required="required" autofocus="autofocus">
   </textarea>

see how it should be (closing tag on the same line and no spaces)

   <textarea  ....required="required" autofocus="autofocus"></textarea>

What is AJAX?

AJAX, acronym for Asynchronous Javascript and XML, is a web development technique that allows you to create more interactive applications. One of the main goals is to make web page responses faster by exchanging small amounts of information with the web server behind the scenes.

AJAX is loading and rendering a page, using client-side scripting resources, searching and loading data into the background without the need to re-load the page.

  • There is a problem, now it’s only appearing Alert("error sending form"); when sending, I have to add something in form or php ?

  • Yes, it’s all right to send the data to the bank, but it was supposed to appear in Alert("Successfully sent form");... I didn’t touch the code, I just copied and pasted.

  • If you want I can post the updated file.

  • Ready, edited in the post...

  • Already put the name of my bank, I’m reviewing the code to see if I find this error. And THANK you so much your help was essential.

  • 1

    There is no error in the code, both in its edited and in my answer. It must be something local.

  • Yes, I’m using bootstrap, I think it might be something local, I’m using xampp could it be an error in xampp? When I arrive tomorrow in college I take the test with modal. could you help me with this so modal? It has been a little while since I am studying web.

  • @Paulovictor, see the placeholder http://kithomepage.com/sos/form-aluno2.htmbid

Show 3 more comments

2

If it returns 1, it is because it is entered in the if of the archive PHP, what you can do is put a "technical adaptation" on that own if, where the echo will show a alert of JS, if an error occurs, it will return to the previous page, keeping the data:

if( $result = $statement->execute($valores)){
    echo "<script>alert('Dados enviados com sucesso!');location.href = 'index.php';</script>";
} else {
    echo "<script>alert('Ocorreu um erro no envio!');history.back();</script>";
}
  • Guy worked out here, but when the going’s wrong he’s not coming back with the data, could you help me with that thank you.

  • Now it worked. but it has to appear this Alert without the page is blank ?

  • 1

    changes are in the answer, just put the link to where you want to redirect =D

  • 1

    In this solution, you should say that THERE IS NO need to use AJAX, you can remove AJAX that will work the same way because the form is being sent by the HTML form action and AJAX is there silly.

Browser other questions tagged

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