How to send data with ajax so that you do not have to reload the page for the changes to come out?

1

How about, I have an ADD button, which contains two fields, which are filled and the data is sent to the table in mysql and in the table below

By clicking on SAVE to send the data I get this message, but I send it to another page, as I do to come out in the same modal window?

and I have to go back to the page and update so that the data appear, which is annoying, I want it to be done automatically, they told me that with ajax, but I do not know how, I just start and do not use it What do I need, a bookstore? I hope you can help me.

I leave my code for my modal

<!-- Modal-->
<form id="form1" name="form1" method="post" action="agregarModal_validacion.php">
<div id="myModal1" class="modal fade" role="dialog">
  <div class="modal-dialog modal-sm">
    <!-- Modal content-->
    <div class="modal-content"> 
      <!--Cabecera del modal-->
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Nuevo Trabajo</h4>
      </div> 
      <!--Contenido del modal-->
      <div class="modal-body">
      
        <div class="form-group">
          <div class="col-xm-6">
          <input class="form-control" type="text" id="txt_nombre" name="txt_nombre" placeholder="Nombre del trabajo" required="">
          </div>
        </div>
        
        <div class="form-group">
          <div class="col-xm-6">
          <input class="form-control " type="text" id="txt_costo" name="txt_costo" placeholder="Costo" required="">
          </div>
        </div>
      </div> 
      <!--Final del modal-->
      <div class="modal-footer">
        <button type="submit" class="btn btn-success btn-lg" style="width: 100%;"><span class="glyphicon glyphicon-ok-sign"></span> Guardar</button>
      </div>
    </div>
  </div>
</div>
</form>  

And the code of my php that makes the query

<?
$conexion= mysqli_connect("localhost", "root", "root", "registros");
if($conexion)
{


  //Variables
  
  $Nombre_Trabajo = $_POST['txt_nombre'];
  $Costo=$_POST['txt_costo'];


//realiza la consulta
  $consulta= "INSERT INTO trabajos (Nombre_Trabajo, Costo) values ('$Nombre_Trabajo','$Costo')";
  
  

//para ejecutar consulta
  $resultado=mysqli_query($conexion ,$consulta);
 
  if ($resultado) 
  { 
    $messages[]  = "Los datos han sido agregados correctamente";
  }
    
  else 
  {
    $errors[]= "No se puedo realizar la accion";
  } 
      
if (isset($errors)){
      
      ?>
      <div class="alert alert-danger" role="alert">
        <button type="button" class="close" data-dismiss="consulta_lista.php">&times;</button>
          <strong>Error!</strong> 
          <?php
            foreach ($errors as $error) {
                echo $error;
              }
            ?>
      </div>
      <?php
      }

if (isset($messages)){
        
        ?>
        <div class="alert alert-success" role="alert">
            <button type="button" class="close" data-dismiss="myModal1">&times;</button>
            <strong>¡Bien hecho!</strong>
            <?php
              foreach ($messages as $message) {
                  echo $message;
                }
              ?>
        </div>
        <?php
      }

  

}
  else{ 
        echo ""; 
      }
        mysqli_close($conexion);   
      ?> 
    
asked by Root93 03.11.2016 в 01:23
source

3 answers

1

The modal leaves the form and removes submit by button, in it you add an id and already with the Jquery you do it:

$(document).ready(function () {
$("#idTuboton").click(function () {
   var data = form.serialize();
   $.post('urlDetuPhp',data,function (data) {
       $('#respuesta').html(data);
    });
 });
});

Button:

<button type="button" class="btn btn-success btn-lg" style="width: 100%;" id="idTuboton><span class="glyphicon glyphicon-ok-sign"></span> Guardar</button>

It is simply to accommodate it to your liking and in the php file to make the insert, that if, make an alert of the data so that you can see how it is sent ... The rest is already a bit of imagination and self-taught ...

    
answered by 03.11.2016 в 02:31
1

It is very easy to implement, first you must eliminate your action of the form tag of your form and secondly you must create a box to get the AJAX response.

Example:

<form id="form1" name="form1" method="POST">
   <!-- Tus inputs -->
</form>

<div id="respuesta"><!-- Respuesta AJAX --></div>

On the same page as your form, you must add AJAX

$(document).ready(function(){   
    $(document).on('submit', '#form1', function() { 

        //Obtenemos datos formulario.
        var data = $(this).serialize(); 

        //AJAX.
        $.ajax({  
            type : 'POST',
            url  : 'agregarModal_validacion.php',
            data:  data, 

            success:function(data) {  
                $('#respuesta').html(data).fadeIn();
            }  
        });
        return false;
   });
});//Fin document.
  

Note: Important to add the library of jQuery in your document HTML , it would be between the <head></head>

tag

Complete Example:

<!DOCTYPE html>
<html lang ="es-ES">
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

    <script>
      $(document).ready(function(){   
         $(document).on('submit', '#form1', function() { 

              //Obtenemos datos formulario.
              var data = $(this).serialize(); 

              //AJAX.
              $.ajax({  
                 type : 'POST',
                 url  : 'agregarModal_validacion.php',
                 data:  data, 

                 success:function(data) {  
                     $('#respuesta').html(data).fadeIn();
                 }  
              });
              return false;
        });
      });//Fin document.
    </script>        
</head>
<body>
   <!-- tu formulario -->
   <form id="form1" name="form1" method="POST">
      <!-- Tus inputs -->
   </form>

   <div id="respuesta"><!-- Respuesta AJAX --></div>
</body>
</html>

addModal_validation.php

You continue with your code PHP , it is important that the file PHP matches the URL of AJAX .

    
answered by 29.07.2017 в 14:10
0

So that this does not happen the most logical way is that your modal is not a <form> and thus save the submit of your button once you click on the button flames at ajax and in success update the values you receive from your ajax response

The click of the button must now work with jquery

Button

<button id="guardar" class="btn btn-success btn-lg" style="width: 100%;"><span class="glyphicon glyphicon-ok-sign"></span> Guardar</button>

Click

$('#guardar').click(function(){
       var parametros = {
            "nombre" : $("#txtNombre").val(),
            "costo" : $("#txtCosto").val()
      }
      $.ajax({
              data : parametros,
              url : "agregarModal_validacion.php"
              type : "post"
              success : function(response){
                     //response contiene la respuesta al llamado de tu archivo
                     //aqui actualizas los valores de inmediato llamando a sus respectivas id.
              }
       })
});

You must modify the response of your PHP file and leave it as JSON

    
answered by 03.11.2016 в 01:31