Using AJAX with CRUD

0

Good evening,

I have made a CRUD for an information request form from an academy. The idea is to use AJAX to make the CRUD much more dynamic and effective, but I'm still new to AJAX and I do not have much idea to be honest.

This is the CRUD:

For the table I use the Datatables

plugin

This is my file structure:

For the View, it's in index / languageacademy / request-information.php

The code in the table is as follows:

<table class="table table-striped table-bordered table-hover" id="solicitudinfo" data-order='[[ 0, "desc" ]]'>
<script>

    $(document).ready( function () {
        $('#solicitudinfo').DataTable( {} );
        $('[data-toggle="tooltip"]').tooltip(); 
    } );

</script>
    <thead>
        <tr>
            <th>ID</th>
            <th>Fecha</th>
            <th>Centro</th>
            <th>Nombre</th>
            <th>Curso</th>
            <th>Edad</th>
            <th>Contacto</th>
            <th>Etiquetas</th>
            <th>Acciones</th>
        </tr>
    </thead>
    <tbody>
    <?php
        $solicitud = new SolicitudInfo;
        $solicitudes = $solicitud->getSolicitudes();
        $totalsolicitudes = count($solicitudes);
        if ($totalsolicitudes > 0){
            foreach ($solicitudes as $solinfo){ 
    ?>
        <tr>
            <td><?php echo $solinfo['IDSolicitud']; ?></td>
            <td><?php echo $solinfo['DiaSolicitud']; ?><br><?php echo $solinfo['HoraSolicitud']; ?></td>
            <td><?php echo $solinfo['Centro']; ?></td>
            <td><?php echo $solinfo['Nombre']; ?>  <?php echo $solinfo['Apellidos']; ?></td>
            <td><?php echo $solinfo['CursoEscolar']; ?></td>
            <td><?php echo getAge($solinfo['FechaNacimiento']); ?> años</td>
            <td><i class="fa fa-phone-square" aria-hidden="true"></i> <?php echo $solinfo['MovilContacto']; ?><br><i class="fa fa-envelope" aria-hidden="true"></i> <?php echo $solinfo['EmailContacto']; ?></td>
            <td><span class="label label-default green" style="background-color:#32C5D2;border-radius: 5px !important;">Nueva Solicitud</span></td>
            <td>
                <a class="btneliminarsolinfo btn" data-id="<?php echo $solinfo['IDSolicitud']; ?>" data-action="remove" style="background-color:#FF0206;border: 0px !important;color:white;" data-toggle="confirmation" title="¿Eliminar Solicitud?" data-singleton="true"> <i class="fa fa-trash" aria-hidden="true"></i> </a>
                <button type="button" class="btn" style="background-color:#1b9e1d;border: 0px !important;color:white;" data-toggle="tooltip" title="Ver Solicitud"><i class="fa fa-eye" aria-hidden="true"></i></button>
                <button type="button" class="btn" style="background-color:#5172F3;border: 0px !important;color:white;" data-toggle="tooltip" title="Editar Solicitud"><i class="fa fa-pencil-square-o" aria-hidden="true"></i></button>
                <button type="button" class="btn" style="background-color:#EDC30F;border: 0px !important;color:white;" data-toggle="tooltip" title="Añadir Etiqueta"><i class="fa fa-tags" aria-hidden="true"></i></button>
                <div id="resultado-mi-formulario"></div>
            </td>
        </tr>
    <?php   
            }
        }
    ?>
    </tbody>
</table>

Then I have the file ajax.js in index / assets / ajax.js where I want to put all the ajax code to delete an item, edit it, see it in a modal, add it from a modal, etc.

this is the ajax code (Echo with the help of @ D.Bulton):

$(document).ready(function() {              
    $(document).on('submit', '#solicitudinfo', function() {   
        //Obtenemos datos.          
        var data = $(this).serialize();

        $.ajax({            
            type : 'POST',
            url  : '../assets/webla/solicitudinfo.php',
            data : data,
            success :  function(data) {                 
                $("#resultado-mi-formulario").html(data).fadeIn();
            },
            complete: function(){
               setTimeout(function() {
               }, 15000);    
            }
        });         
        return false;           
    });
     //Boton eliminar.
     $(".btneliminarsolinfo").click(function(e) {

         e.preventDefault();
         //Variable con el valor del boton.
         var id = $(this).attr('data-id');
         var action = $(this).attr('data-action');   

         //Ajax.
         $.post('../assets/webla/solicitudinfo.php', {
            Id:id,
            Action: action
         },function(supr) {
            if (supr=='0') {          
               location.href="solicitud-informacion.php";
            }
         }); 
    });
});

And then there is the requestinfo file in index / assets / webla / solicitudinfo.php with the code:

 <?php 

    require_once("../classes/class.sistema.php");
    require_once("../classes/class.solicitudinfo.php");
    require_once("../functions.php");

    $solicitud = new SolicitudInfo;

    if ($_POST['action'] == "insert") {
        $centro = secure($_POST['centro']);
        $curso = secure($_POST['curso']);
        $nombre = ucwords(strtolower(secure($_POST['nombre'])));
        $apellido = ucwords(strtolower(secure($_POST['apellidos'])));
        $fechanacimiento = secure($_POST['fechanacimiento']);
        $poblacion = ucwords(strtolower(secure($_POST['pueblo'])));
        $codpostal = secure($_POST['codpostal']);
        $nombretutor = ucwords(strtolower(secure($_POST['nombretutor'])));
        $apellidostutor = ucwords(strtolower(secure($_POST['apellidostutor'])));
        $email = strtolower(secure($_POST['email']));
        $movil = secure($_POST['movil']);
        $conocen = "Not Answered";
        $atendido = secure($_POST['atendido']);
        $observaciones = ucfirst(strtolower(secure($_POST['observaciones'])));
        $dia = date("d") . "/" . date("m") . "/" . date("Y");
        $hora = date("G") . ":" . date("i") . ":" . date("s");

        $solicitud->addSolicitud($dia, $hora, $centro, $curso, $nombre, $apellido, $fechanacimiento, $poblacion, $codpostal, $nombretutor, $apellidostutor, $email, $movil, $conocen, $observaciones, $atendido);

        if ($solicitud == true) {
            echo "<script>swal('Confirmación', 'Se ha añadido la nueba solicitud.', 'success')</script>";
        } else {
            echo "<script>swal('Error', 'Ha ocurrido un problema al enviar la solicitud de información. Inténtelo de nuevo o llame al 902 024 890.', 'error')</script>";
        }
    };

    if ($_POST['Action'] == "remove") {
        $id = $_POST['Id'];

        $solicitud->deleteSolicitud($id);

        //Respuesta ajax, va redirigirnos al index o donde une quiera.
        echo "0";

    };

?>

So these are my problems:

  • The form to insert new applications works through ajax perfectly, but I have two problems with it:

    • Once you give it to send, the bootstrap modal remains open and you have to manually close it to see the confirmation notification. I tried to add to the submit button the data-miss "#modal" but then it does not send the form. How could I close the modal once the form is sent?
  • I do not know how to update the table once the new request has been inserted.

  • The button to delete the request does not work and does not update the table either

  • How would you send information to a modal with ajax?

  • I want to use the data-action="remove / edit / insert" attribute so that in the requestinfo.php file I can use if ($ _POST ['action'] == "".

These are my doubts with the subject of ajax in a CRUD. If I have forgotten some information or need more information, I will try to add it as soon as possible.

    
asked by Charlie Clewer 24.09.2017 в 21:29
source

1 answer

0

Execute the following line of code in the success method of the ajax, replace the jQuery selector with the id of the modal you want to close: -

$('#idDelModalACerrar').modal('hide'); // cierra el modal.

To update the table: -  As you have proposed the part of printing information in the table, you should reload the page to update it, since you use php to print it. If you use javascript to show data in the table, you could make ajax calls to bring the data from the server and print them.

Remove html part: -  It gives me that the element is not defined correctly, it can be seen that it has a different color. Check it for that matter, look at the source code of the page.

To show data in a modal you can do it in the following way.

function ajaxCall() { 
  var modal = $("#myModal");
  var modalBody = $('.modal-body');

  $.get('http://www.json-generator.com/api/json/get/cfoiAssjPC?indent=3')
  .done(function(res) {
    modalBody.html(table(res[0]));
    modal.modal('show');
  })
  .fail(function(err) {
     modalBody.html("Error: "  + err);
  });
}

function table(obj) {
  var tabl = "<table class='table table-responsive'><th>Company</th><th>Phone</th><th>Address</th>";
  var tr = '<tbody><tr>';
  tr +="<td>"+obj['company']+"</td>";
  tr +="<td>"+obj['phone']+"</td>";
  tr +="<td>"+obj['address']+"</td>";
  tr += "</tr>";
  tabl += tr + "</tbody></table>";
  return tabl;
}
<meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
    
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
      
    </div>
  </div>
<button onclick="ajaxCall()">Mostrar Datos en modal</button>
    
answered by 24.09.2017 / 23:15
source