2

I have a form from where the user imput data to the database and a php file with the function to do so. I'd like to show an alert message on the same form page using javascript without refresing the page. I don't know much about JS and I have tried every possible solution I came across but I cannot find the solution yet, what am I doing wrong? I hope someone could help me.

Edit: I decided to use modals to do this but modal is not showing and PHP file gets opened

Edit 2: I got it to show the modal on screen, but It has no message, not even the title specified in the h4 tags

What I'd like the user to see as message is the echo in the PHP file.

this is what I tried:

form code:

<form role="form" id="frmUsuario">
                    <div class="row">
                      <div class="col-sm-6 form-group">
                            <label for="name"> ID Usuario:</label>
                            <input type="text" class="form-control" id="IDUsuario" name="txtIDUsuario" readonly>
                    </div>
                    <div class="row">
                        <div class="col-sm-6 form-group">
                            <label for="name"> Nombre Comercial:</label>
                            <input type="text" class="form-control" id="NombreComercial" name="txtNombreComercial" required>
                        </div>
                        <div class="col-sm-6 form-group">
                            <label for="email"> Nombre del Representante:</label>
                            <input type="text" class="form-control" id="NombreRepresentante" name="txtNombreRepresentante" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-12 form-group">
                            <label for="message"> Expediente:</label>
                            <textarea style="resize:none" class="form-control" type="textarea" id="Expediente" name="txtExpediente" maxlength="6000" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-12 form-group">
                            <label for="message"> Observaciones:</label>
                            <textarea style="resize:none" class="form-control" type="textarea" id="Observaciones" name="txtObservaciones" maxlength="6000" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-12 form-group">
                            <button type="submit" name="btnEnviarUsuario" id="EnviarUsuario" class="btn btn-lg btn-default pull-right" >Enviar &rarr;</button>
                        </div>
                        <div class="col-sm-12 form-group">

                                </div>
                              </form>

Modal:

    <!-- Modal -->
<div class="modal fade" id="ModalMSJ" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" style="font-weight: bold;" id="exampleModalLabel">Usuario</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body" id="MSJ">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

JS function in the form page:

    <script type="text/javascript">
$("#frmUsuario").submit(function(e){
    e.preventDefault();
    var btnEnvUsuario="EnviarUsuario"; //name
    $.ajax({
        type : 'POST',
        data: $("#frmUsuario").serialize()+"&btnEnviarUsuario="+btnEnvUsuario,
        url : 'Logica/Usuario.php',
        success : function(data){
            $("#MSJ").html(data);
            $("#ModalMSJ").modal("show");
        }
    });
    return false;
}); 
</script>

PHP file:

$IDUsuario=$_POST["txtIDUsuario"];
$NombreRepresentante=$_POST["txtNombreRepresentante"];
$NombreComercial=$_POST["txtNombreComercial"];
$Expediente=$_POST["txtExpediente"];
$Observacion=$_POST["txtObservaciones"];

if(isset($_POST["btnEnviarUsuario"]))
{
   $Conexion = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

    if ($Conexion->connect_error) 
    {
        die("Connection failed: " . $Conexion->connect_error);
    }

    $sql = "insert into usuario
                (NombreRepresentante,NombreComercial,Expediente,Observacion)
                values
                ('$NombreRepresentante','$NombreComercial','$Expediente','$Observacion');";

        if($Conexion->query($sql) === TRUE) { 


        /*Message I'd like to show to user*/

          echo "Usuario guardado exitosamente";
}
Errol Chaves Moya
  • 307
  • 2
  • 5
  • 20
  • 1
    I think you could consider using https://getbootstrap.com/docs/4.0/components/modal/#live-demo modal from bootstrap, and just show the modal using bootstrap https://getbootstrap.com/docs/4.0/components/modal/#via-javascript and make the modal hidden, and show the modal and fill the modal when it's succesfull. see https://stackoverflow.com/a/28924587/4906348 for references. On Success you could also do alert directly without print out or put the page on success function – Benyamin Limanto Feb 15 '19 at 18:14
  • I see what your doing, and you're really on the right track. Consider this, It costs money to send content over the internet. The more data, the more money. I say this to note that sending java script after the first page load is becoming a bad practice. It completely acceptable to load a new JS file after the page load, or well into the session, but the means to do so should be loaded on the first request. – Richard Tyler Miles Feb 15 '19 at 18:21
  • also the selector you're using is likely to not work on older browsers. I recommend using alphanumeric charaters only. https://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html – Richard Tyler Miles Feb 15 '19 at 18:25
  • thanks for replying, I'll try this out and let you know. – Errol Chaves Moya Feb 15 '19 at 18:36
  • **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli / PDO. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Feb 15 '19 at 20:56
  • 1
    @BenyaminLimanto I decided to follow your advice and use modals. I edited my question because modal is not showing and PHP file executes...could you help me out? Thanks. – Errol Chaves Moya Feb 16 '19 at 09:22

3 Answers3

2

Just remove the form tag and it won't fully refresh the page.

Then remove your alert from the php file and put it as shown below

<script>
$(document).ready(function(){
$("#EnviarUsuario").click(function(){
    $.ajax({
        url: "Logica/Usuario.php",
        type: 'post',
        data: {"btnEnviarUsuario":document.getElementByName("EnviarUsuario").value},

        success: function(result){
           //You put here your alert
           alert("Usuario guardado exitosamente");
        }
    });
});
});
</script>
Donny
  • 516
  • 3
  • 9
  • What if I want to get the success alert from an echo in the Usuario.php instead of writing it myself? – Errol Chaves Moya Feb 15 '19 at 18:51
  • 1
    With AJAX the php script is executed in the background so you won't see its output. The best you can do is make the php script print a JSON and parse it with JavaScript in the success function of JS AJAX – Donny Feb 15 '19 at 19:10
  • @ErrolChavesMoya or the PHP could echo plain text, or HTML, and you can then display that inside an element somewhere in your page. What you _can't_ do is what your PHP in the original question does, which is to spit out a ` – ADyson Feb 15 '19 at 20:55
1

seems you having problem for using bootstrap. I wrap it using jsfiddle and fake JSON API. You could try it. I Hope it help. It's just simple problem that you have there. , your code is wrong on the ajax data.

see this. https://jsfiddle.net/hp9jzfmo/1/

$(function(){
  $("#frmUsuario").submit(function(e){
      e.preventDefault();
      var btnEnvUsuario=$('#EnviarUsuario').val();
      $.ajax({
          type : 'POST',
          data: $("#frmUsuario").serialize(), // This is the right one
          url : 'https://jsonplaceholder.typicode.com/posts',
          success : function(data){
              $("#MSJ").html(JSON.stringify(data));
              $("#ModalMSJ").modal('show');
          }
      });
      return false;
  }); 
});

the body should be

<form role="form" id="frmUsuario">
  <div class="row">
    <div class="col-sm-6 form-group">
      <label for="name"> ID Usuario:</label>
      <input type="text" class="form-control" id="IDUsuario" name="txtIDUsuario" readonly>
    </div>
    </div>
    <div class="row">
      <div class="col-sm-6 form-group">
        <label for="name"> Nombre Comercial:</label>
        <input type="text" class="form-control" id="NombreComercial" name="txtNombreComercial" required>
      </div>
      <div class="col-sm-6 form-group">
        <label for="email"> Nombre del Representante:</label>
        <input type="text" class="form-control" id="NombreRepresentante" name="txtNombreRepresentante" required>
      </div>
    </div>
    <div class="row">
      <div class="col-sm-12 form-group">
        <label for="message"> Expediente:</label>
        <textarea style="resize:none" class="form-control" type="textarea" id="Expediente" name="txtExpediente" maxlength="6000" rows="3"></textarea>
      </div>
    </div>
    <div class="row">
      <div class="col-sm-12 form-group">
        <label for="message"> Observaciones:</label>
        <textarea style="resize:none" class="form-control" type="textarea" id="Observaciones" name="txtObservaciones" maxlength="6000" rows="3"></textarea>
      </div>
    </div>
    <div class="row">
      <div class="col-sm-12 form-group">
        <button type="submit" name="btnEnviarUsuario" id="EnviarUsuario" class="btn btn-lg btn-default pull-right" >Enviar &rarr;</button>
      </div>
    </div>

</form>
<!-- Modal -->
<div class="modal fade" id="ModalMSJ" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" style="font-weight: bold;" id="exampleModalLabel">Usuario</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body" id="MSJ">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

The PHP Part I think you could do your self, as far as the data passed to server. I hope it helps :)

Benyamin Limanto
  • 775
  • 10
  • 24
  • you were right. It seemed the problem was the way I pass the varibles thru ajax. I got it to show the modal on screen, but It has no message, not even the title specified in the

    what could be wrong? I updated the JS code. Thanks for your help
    – Errol Chaves Moya Feb 16 '19 at 15:21
  • @ErrolChavesMoya no error from PHP? Do you try using the developer tools on web browser? – Benyamin Limanto Feb 17 '19 at 04:25
  • 2
    I noticed something peculiar after the modal appeared on screen: the button text color was white And I thought 'what if the modal title and body text are white too?' So I tried to select some text on the modal and just as I thought, the message was there the whole time. However I could not see it because the text and the modal window color was white ha ha. Anyway thank you so much for your suggestion on using modals, I learn something new and at the end, it was way easier than my original ideal. And thank you for all your help, I really apreciate it. – Errol Chaves Moya Feb 17 '19 at 08:28
  • Ur welcome. It's nice to see other people can solve problem. – Benyamin Limanto Feb 17 '19 at 09:08
1

This is the final solution:

Form Code:

<form role="form" id="frmUsuario">
                <div class="row">
                  <div class="col-sm-6 form-group">
                        <label for="name"> ID Usuario:</label>
                        <input type="text" class="form-control" id="IDUsuario" name="txtIDUsuario" readonly>
                </div>
                <div class="row">
                    <div class="col-sm-6 form-group">
                        <label for="name"> Nombre Comercial:</label>
                        <input type="text" class="form-control" id="NombreComercial" name="txtNombreComercial" required>
                    </div>
                    <div class="col-sm-6 form-group">
                        <label for="email"> Nombre del Representante:</label>
                        <input type="text" class="form-control" id="NombreRepresentante" name="txtNombreRepresentante" required>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-12 form-group">
                        <label for="message"> Expediente:</label>
                        <textarea style="resize:none" class="form-control" type="textarea" id="Expediente" name="txtExpediente" maxlength="6000" rows="3"></textarea>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-12 form-group">
                        <label for="message"> Observaciones:</label>
                        <textarea style="resize:none" class="form-control" type="textarea" id="Observaciones" name="txtObservaciones" maxlength="6000" rows="3"></textarea>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-12 form-group">
                        <button type="submit" name="btnEnviarUsuario" id="EnviarUsuario" class="btn btn-lg btn-default pull-right" >Enviar &rarr;</button>
                    </div>
                    <div class="col-sm-12 form-group">

                            </div>
                          </form>

Modal Code

<div class="modal fade" id="ModalMSJ" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                                  <div class="modal-dialog" role="document">
                                    <div class="modal-content">
                                      <div class="modal-header">
                                        <h4 class="modal-title" style="font-weight: bold; color:black;" id="exampleModalLabel">Usuario</h4>
                                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                          <span aria-hidden="true">&times;</span>
                                        </button>
                                      </div>
                                      <div class="modal-body" style="color:red;" id="MSJ">
                                      </div>
                                      <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                      </div>
                                    </div>
                                  </div>
                                </div>

JS Code:

    <script type="text/javascript">
$("#frmUsuario").submit(function(e){
    e.preventDefault();
    var btnEnvUsuario="EnviarUsuario"; //variable to check if user clicked the button
    $.ajax({
        type : 'POST',
        data: $("#frmUsuario").serialize()+"&btnEnviarUsuario="+btnEnvUsuario,
        url : 'Logica/Usuario.php',
        success : function(data){
            $("#MSJ").html(data);
            $("#ModalMSJ").modal("show");
        }
    });
    return false;
}); 
</script>

PHP File Code:

   $IDUsuario=$_POST["txtIDUsuario"];
$NombreRepresentante=$_POST["txtNombreRepresentante"];
$NombreComercial=$_POST["txtNombreComercial"];
$Expediente=$_POST["txtExpediente"];
$Observacion=$_POST["txtObservaciones"];

if(isset($_POST["btnEnviarUsuario"]))
{
   $Conexion = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

    if ($Conexion->connect_error) 
    {
        die("Connection failed: " . $Conexion->connect_error);
    }

    $sql = "insert into usuario
                (NombreRepresentante,NombreComercial,Expediente,Observacion)
                values
                ('$NombreRepresentante','$NombreComercial','$Expediente','$Observacion');";

        if($Conexion->query($sql) === TRUE) { 


        /*Message I'd like to show to user*/

          echo "Usuario guardado exitosamente";
}
Errol Chaves Moya
  • 307
  • 2
  • 5
  • 20