How do I send data from a modal window with ajax and php to mysql?

1

I have a modal window that sends data to a table in mysql called (jobs) that has three fields (Job_id, Job_Name and Cost) and likewise shows that data in the table in html

My problem is that when sending the data, I get a message that it was correctly, but I sent it to another page and I have to return to the previous page and reload to update, I want that message to me come out in my modal window, or in my page where I have my table (consult_list.php), they told me to use ajax, but I do not know how it is done, I have the following in my file (add_modal.php), so that it runs I have to have a bookstore, do not I know maybe jquery or something? and if it's okay to put my script in that file? or can I place it where I have my table?

<script type="text/javascript">
$('#guardar').click(function(){
       var parametros = {
            "nombre" : $("#txt_nombre").val(),
            "costo" : $("#txt_costo").val()
      }
      $.ajax({
              data : parametros,
              url : "agregarModal_validacion.php"
              type : "post"
              success : function(response){
                     
              }
       })
});
</script>


<!-- Modal-->
<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" id="guardar" class="btn btn-success btn-lg" style="width: 100%;"><span class="glyphicon glyphicon-ok-sign"></span> Guardar</button>
      </div>
    </div>
  </div>
</div>

Is it correct in this way? or how else can I do it? and is that they told me that in my php change the answer and leave it with json, but what is that? How do I do it? I hope you can help me please, I leave my code for my php

<?php

 ?>

        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minium-scale=1.0">
        <link rel="stylesheet" href="css/bootstrap.min.css"> 
<?
$conexion= mysqli_connect("localhost", "root", "root", "registros");
if($conexion)
{
//Variables
  $Nombre_Trabajo = $_POST['nombre'];
  $Costo=$_POST['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 04.11.2016 в 05:47
source

2 answers

1
$.ajax({
               data : parametros,
               url : "agregarModal_validacion.php"
               type : "post"
               success : function(response){
                   //Recibes la respuesta y la muestras en un div
                   var mensaje = response.message;
               }
    })

In the success you receive the response from the server to your ajax request, here in the response variable you have the answer, which in your case will be error or the data has been added correctly. Now in the server part you keep these messages in a variable and code it in JSON format:

$jsondata['success'] = true; //En caso de exito
$jsondata['message'] = 'Hola! El valor recibido es correcto.'; // el mensaje
header('Content-type: application/json; charset=utf-8');
echo json_encode($jsondata);
    
answered by 04.11.2016 в 08:37
0

I recommend that you use the advantages of jquery for forms and you will save yourself a lot of problems ...

The new version of jQuery does not accept the functions .click() so you can replace it with $(".clase/#id").on("click", function() {

In this case, I'll give you an example of what I would do ...

<!-- Modal-->
<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> 

        <!-- FORMULARIO -->
        <form action="#" class="modalForm">

          <!--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" id="guardar" class="btn btn-success btn-lg" style="width: 100%;"><span class="glyphicon glyphicon-ok-sign"></span> Guardar</button>
          </div>

       </form>
       <!-- FORMULARIO - END -->

    </div>
  </div>
</div>

Then in the javascript code I would change it in this way ...

$("#myModal1").on("submit", ".modalForm", function(){
    var parametros= {
        "txt_nombre" : $("input#txt_nombre").val(),
        "txt_costo" : $("input#txt_nombre").val()
    };
    $.ajax({
        type: "POST",
        url: "agregarModal_validacion.php",
        data: params,
        success: function(data) {
        },
        error: function() {
        }
    })
    return false; // Esto para evitar que envíe el formulario.
})

I hope that with this code you have learned something new and you adapt to the new version of jQuery:)

    
answered by 04.11.2016 в 09:57