I am working with Laravel 5.8 in which I am using a datatable which I fill dynamically with jquery and the function row.add();
var clase = $("#clase").val();
var fecha_clase = $("#fecha_clase").val();
var hora_clase = $("#hora_clase_input").val();
var duracion_clase = $("#duracion_clase").val();
var profesor = $("#profesor").val();
var vehiculo = $('#vehiculo').val();
var contador = parseFloat(table2.rows().count()) + 1;
var btnEliminar = '<button type="button" class="btn btn-outline-danger elevation-1 btn_eliminar">Quitar</button>';
table2.row.add( [
contador,
fecha_clase,
hora_clase,
duracion_clase,
profesor,
vehiculo,
btnEliminar
] ).draw();
table2.columns.adjust();
With the fnGetData() function of datatable I capture all the data in arrays and transform it to json using JSON.stringify as shown below
var p = $("#tablaAgregados").dataTable().fnGetData();
var json = JSON.stringify(p);
the json that generates me is the following
[
[1,"16/11/2019","17:40","3","47","6","<button type=\"button\" class=\"btn btn-outline-danger elevation-1 btn_eliminar\">Quitar</button>"]
[2,"18/11/2019","20:40","5","48","5","<button type=\"button\" class=\"btn btn-outline-danger elevation-1 btn_eliminar\">Quitar</button>"]
]
Try to send it in this way and other similar ones without success
$.ajax({
url : "{{ route('alumno.horario') }}",
data : json,
method : 'POST',
success : function(response){
alert("funciona bien");
},
error: function(error){
alert("No funciona");
}
});
this is my routeRoute::post('alumno/horario','alumnoController@storeHorario')->name('alumno.horario');
In short, I need to somehow send the data added to the table to my controller, to later save it to the database.
Update
I managed to receive the json in my controller (as shown by the dump() below)
But now I have the problem that when I press the #btnCrear
ajax it indicates an error, even though the controller is correctly receiving the json.
$('body').on('click','#btnCrear', function sendData(){
var p = $("#tablaAgregados").dataTable().fnGetData();
$.ajax({
url:"{{ route('alumno.horario') }}",
type: 'POST',
dataType:'json',
contentType: 'json',
data: JSON.stringify(p),
contentType: 'application/json; charset=utf-8',
success : function(response){
Toast.fire({
type: 'success',
title: 'Su alumno ha sido registrado con éxito'
});
},
error: function(error){
Toast.fire({
type: 'error',
title: 'Ha ocurrido un problema con el registro de horario práctico'
});
}
});
});
my controller function
public function storeHorario(Request $request)
{
$data = json_decode($request->getContent());
}
result withdump($data)
Solution
add
return json_encode($data);
in controller