0

Estoy intentando hacer un crud con ajax sin datatables, pero al agregar un registro no me recarga la tabla. He intentado buscar varios ejemplos pero todos lo hacen con datatables y la idea es hacer mi propia tabla.

<script>

$(document).ready(function(){

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$('#agregar').click(function(){
   $('#modal-agregar').modal('show');
});

$('#btn-agregar').click(function(e){
    e.preventDefault();

    var tabla = $("#table-movies");
    var title = $('#title').val();
    var premiere = $('#premiere').val();
    

 $.ajax({
      type: "POST",
      url: "/peliculas/guardar",
      dataType: "json",
      data: {
          title: title,
          premiere: premiere
      },
      success: function(data){
        $('#modal-agregar').modal('hide');
         $('#form-peliculas')[0].reset();
         tabla.fnDraw();
      },
      error: function(data){
        alert(data);
      }
  });
});

});

1 respuesta 1

0

No veo la info de tu tabla así que utilicé una tabla genérica.

<table id="table" class="table container-sm">
  <thead>
    <tr><th colspan="4">Tabla de películas</th></tr>
  <tr>
    <th>#</th>
    <th>Título</th>
    <th>Premiere</th>
  </tr>
  </thead>
  <tbody>

  </tbody>
</table>

  1. En Ajax yo lo utilizo con el Done, Fail y Always:

 $.ajax({
            type: "POST",
            url: "/peliculas/guardar",
            data: {
                   title: title,
                   premiere: premiere
            },
            dataType: "json"
        })
            .done(function (response, jqXHR, textStatus) {                                  
                    $("#table tbody").append(
                        "<tr><td>" + response.id + "</td><td>" + response.titulo + "</td><td>" + response.premiere + "</td></tr>"
                    );
                    form.trigger("reset");
                 
            })
            .fail(function () {
                console.info("Error en el Servidor. Revise los logs.");
            })
            .always(function () {
                console.info("Ejecutado correctamente");
            });

Explicación El response obtenido en el done() lo añado dentro del tbody con el append. Este código lo he probado yo en un pequeño proyecto y si funciona.

Te recomiendo el DataTables

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.