Displaying successful Alert() on the same page. PHP, Html

Asked

Viewed 998 times

2

I wanted to send the message of success or error after registering products from my site on the same page, without loading a new blank with the message, I saw similar questions, some using ajax that have not learned anything yet and could not solve my problem with the topics I found here.

Register of Category:

<form method="post" action="gravacategoria.php">
<div class="container">
<div class="form-group">
    <label class="col-md-4 control-label" for="txtproduto">Nova Categoria: </label>  
    <div class="col-md-6">
    <input id="txtcategoria" name="txtcategoria" type="text" class="form-control input-md" required="">
    </div>
</div>
<div class="form-group">
  <label class="col-md-4 control-label" for="btnsalvar"></label>
  <div class="col-md-8">
    <button id="btnsalvarcat" name="btnsalvar" type="Submit" class="btn btn-primary">Salvar</button>
    <button id="btncancelar" name="btncancelar" class="btn btn-danger">Cancelar</button>
  </div>
</div>
</div>
</form>

Gravacategoria:

<?php
    $conn= new PDO("mysql:host=localhost:3306;dbname=loja","root","aula");

    #$idcategoria=$_POST["txtid"];
    $nomecat=$_POST["txtcategoria"];

    $stmt = $conn->prepare('Insert into loja.categoria(nome)Values(:par_categoria)');

    #$stmt->bindValue(1,$idcategoria);
    $stmt->bindValue(2,$nomecat);     

    $dados=array(":par_categoria"=>$nomecat);

    $result = $stmt->execute($dados);

    if($result){
        echo ("Produto inserido com sucesso");
    }
    else{
        echo("Erro");
    }

Thank you!

  • 1

    Well, the solution is, in fact, with AJAX. Start by studying it. There are functions like fetch Javascript or libraries like Jquery, Axios, among others, that can make your life easier. Good luck.

3 answers

3


A simple solution is to send the data to an iframe on the same page. Just put it on the page:

<iframe name="gravar" style="display: none;"></iframe>

And in the form put a target pointing to the name iframe:

<form target="gravar" method="post" action="gravacategoria.php">
         ↑

In PHP, instead of echo you call a script with the alert of the message, but first it is necessary to make a if to check whether the $_POST is not empty:

<?php
$nomecat=$_POST["txtcategoria"];

if(!empty($nomecat)){
    $conn= new PDO("mysql:host=localhost:3306;dbname=loja","root","aula");

    #$idcategoria=$_POST["txtid"];

    $stmt = $conn->prepare('Insert into loja.categoria(nome)Values(:par_categoria)');

    #$stmt->bindValue(1,$idcategoria);
    $stmt->bindValue(2,$nomecat);     

    $dados=array(":par_categoria"=>$nomecat);

    $result = $stmt->execute($dados);

    if($result){
        $mensagem = "Produto inserido com sucesso";
    }
    else{
        $mensagem = "Erro";
    }
?>
<script>
alert("<?php echo $mensagem ?>");
</script>
<?php    
}
?>
  • Thanks Sam, it’s much better this way. It would be too complicated for the message to be displayed in form that are cancel and save buttons?

  • You’re welcome. Dude, you can do the message the way you want it. Just use parent in the iframe script, something like parent.document.getElementById("msg").innerHTML = "<?php echo $mensagem ?>";, where msg would be the id of an element that would receive the message, for example: <div id="msg"></div>

  • I’m using <iframe name="save" style="display: None;"></iframe> the way it was, then in the script of gravacategory, I upload Alert so : if($result){ $message = "Product successfully inserted"; } Else{ $message = "Error"; } ? > <script> Parent.document.getElementById("msgaqui"). innerHTML = "<? php echo $message ? >"; </script> I added <div id="msg"></div> inside my category registration form just below the buttons. but continues a box message on the screen

  • Still the Alert? It was not to appear more since you removed it.

  • It worked out, buddy, thank you very much

  • I’m new in the forum, Windows seems to understand php I have a question about how to accept the input user data as coins, because when I go to test if I put the product value with (comma) not registered in the database and the precise error by with (dot). I need to open a new question for this or I can ask you here ?

  • Come in in this chat

  • You can make a personalized message with the bootstrap modal, returning json. And really, with ajax will be much better

  • @adventistaam gives yes, but not even know if the guy is wearing bootstrap :D.

  • I’m using bootstrap more like I said I don’t know anything about ajax yet, thanks to all the tips, Sam’s solution was what I needed, at least until I learned Javascript. Thank you

Show 5 more comments

2

Really with ajax and json would be pretty cool, too.

Take a look

On this page I’m using bootstrap, it’s just html, but use the following separate codes:

HTML, JS and PHP

HTML

const msgArr = [
{title: 'Success', msg: 'Salvo com sucesso'},
{title: 'Error', msg: 'Falha ao tentar salvar'},
]

 $('#btnsalvarcat').on('click',function(e){
     e.preventDefault()
     salvarDados()
 })

salvarDados = () =>{
   const idx = getRandomIntInclusive( 0, 1 )
   alert( msgArr[ idx ].msg)
}




function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  
  
  <form method="post" action="gravacategoria.php">
<div class="container">
<div class="form-group">
    <label class="col-md-4 control-label" for="txtproduto">Nova Categoria: </label>  
    <div class="col-md-6">
    <input id="txtcategoria" name="txtcategoria" type="text" class="form-control input-md" required="">
    </div>
</div>
<div class="form-group">
  <label class="col-md-4 control-label" for="btnsalvar"></label>
  <div class="col-md-8">
    <button id="btnsalvarcat" name="btnsalvar"  class="btn btn-primary">Salvar</button>
    <button id="btncancelar" name="btncancelar" class="btn btn-danger">Cancelar</button>
  </div>
</div>
</div>
</form>

In your javascript Voce could use so:

 salvarDados = () => {
    $.ajax({
      url: 'gravacategoria.php',
      type: 'post',
      dataType: 'json',
      data: {
         txtcategoria: $('#txtcategoria').val()
      }
   }).then( r =>{ // o r é o retorno do php
        if(r.status == true){
          alert('Salvo com sucesso!')
        }else{
          alert('Falha ao salvar!')

        }
    })
}

In php

<?php
$nomecat=$_POST["txtcategoria"];

if(!empty($nomecat)){
    $conn= new PDO("mysql:host=localhost:3306;dbname=loja","root","aula");

    #$idcategoria=$_POST["txtid"];

    $stmt = $conn->prepare('Insert into loja.categoria(nome)Values(:par_categoria)');

    #$stmt->bindValue(1,$idcategoria);
    $stmt->bindValue(2,$nomecat);     

    $dados=array(":par_categoria"=>$nomecat);

    $result = $stmt->execute($dados);

    if($result){
        $t = array('status' = true);
        echo json_encode(  $t );
    }
    else{
        $t = array('status' = false);
        echo json_encode(  $t );
    }
?>

}
?>

Who will return to the ajax is the json Encode, where inside it you place the array

That’s the suggestion and that’s how ajax works

  • Thanks for the tip, but in order to use I need to estuar ajax, a lot of things I do not understand

  • The solution was legal.

-1

php form.:

    <form method="post" action="gravacategoria.php">
       <div class="container">
          <div class="form-group">
             <label class="col-md-4 control-label" for="txtproduto">Nova Categoria: </label>  
             <div class="col-md-6">
                <input id="txtcategoria" name="txtcategoria" type="text" class="form-control input-md" required="">
             </div>
          </div>
          <div class="form-group">
             <label class="col-md-4 control-label" for="btnsalvar"></label>
             <div class="col-md-8">
                <button id="btnsalvarcat" name="btnsalvar" type="Submit" class="btn btn-primary">Salvar</button>
                <button id="btncancelar" name="btncancelar" class="btn btn-danger">Cancelar</button>
             </div>
             <div>
                <p><?=$_GET['mensagem']?></p>
             </div>
          </div>
       </div>
    </form>

gravacategoria.php:

<?php
$conn= new PDO("mysql:host=localhost:3306;dbname=loja","root","aula");

#$idcategoria=$_POST["txtid"];
$nomecat=$_POST["txtcategoria"];

$stmt = $conn->prepare('Insert into loja.categoria(nome)Values(:par_categoria)');

#$stmt->bindValue(1,$idcategoria);
$stmt->bindValue(2,$nomecat);     

$dados=array(":par_categoria"=>$nomecat);

$result = $stmt->execute($dados);

if($result){
    $mensagem = "Produto inserido com sucesso";
    header("Location: formulario.php?mensagem=$mensagem");
}
else{
    $mensagem = "Erro";
    header("Location: formulario.php?mensagem=$mensagem");
}
  • That’s not what he wants. He doesn’t want to reload the page.

Browser other questions tagged

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