I am trying to save the data of an excel, using a file-type input to select it, I recently managed to do it without ajax, and it turned out well; However, I have not been able to do it using Ajax. When I researched, I read that to send data from a file type input, you must use FormData () but it is not working, I leave my Ajax code.
The AJAX in my Vista document
$(document).ready(function() {
//-----------Cargar la lista de usuarios dependiendo del perfil----------
$("#id_tip").change(function() {
$("#id_tip option:selected").each(function() {
id_tip = $('#id_tip').val();
$.post("<?php echo base_url();?>cHorarios/cargar_usuarios", {
id_tip : id_tip
},
function(data) {
$("#rut_usu").html(data);
});
});
});
//---------------------fin de la funcion----------------------------------
//-------Enviamos los datos por Ajax -------------------------------------
$(function(){
$('#subida').submit(function(){
var comprobar = $('#file').val().length;
if(comprobar>0){
var formulario = $('#subida');
var rut_usu;
var fecha_ini;
var fecha_ter;
var archivos = new FormData();
archivos.append('rut_usu',rut_usu);
archivos.append('fecha_ini',fecha_ini);
archivos.append('fecha_ter',fecha_ter);
var url = '<?php echo base_url();?>cHorarios/guardar_horario';
for (var i = 0; i < (formulario.find('input[type=file]').length); i++) {
archivos.append((formulario.find('input[type="file"]:eq('+i+')').attr("name")),((formulario.find('input[type="file"]:eq('+i+')')[0]).files[0]));
}
$.ajax({
url: url,
type: 'POST',
contentType: false,
data: archivos,
processData:false,
success: function(data){
if(data == 'OK'){
$('#respuesta').html('<label style="padding-top:10px; color:green;">Importacion de xlsx exitosa</label>');
return false;
}else{
$('#respuesta').html('<label style="padding-top:10px; color:red;">Error en la importacion del xlsx</label>');
return false;
}
}
});
return false;
}else{
alert('Selecciona un archivo para importar');
return false;
}
});
});
//-------Fin de el envio de datos-----------------------------------------
});
The controller (It's the same as my EXCEL post)
public function guardar_horario(){
if (!empty($_FILES['file']['name'])) {
$pathinfo = pathinfo($_FILES["file"]["name"]);
if (($pathinfo['extension'] == 'xlsx' || $pathinfo['extension'] == 'xls')
&& $_FILES['file']['size'] > 0 ) {
// Nombre Temporal del Archivo
$inputFileName = $_FILES['file']['tmp_name'];
//Lee el Archivo usando ReaderFactory
$reader = ReaderFactory::create(Type::XLSX);
//var_dump($reader);
$reader->setShouldFormatDates(true);
// Abrimos el archivo
$reader->open($inputFileName);
$count = 1;
//Numero de Hojas en el Archivo
foreach ($reader->getSheetIterator() as $sheet) {
// Numero de filas en el documento EXCEL
foreach ($sheet->getRowIterator() as $row) {
// Lee los Datos despues del encabezado
// El encabezado se encuentra en la primera fila
if($count > 1) {
$data = array(
'rut_usu' => $this->input->post('rut_usu'),
'hrs_ini' => $row[0],
'hrs_ter' => $row[1],
'lunes' => $row[2],
'martes' => $row[3],
'miercoles' => $row[4],
'jueves' => $row[5],
'viernes' => $row[6],
'sabado' => $row[7],
'fecha_ini' => $this->input->post('fecha_ini'),
'fecha_ter' => $this->input->post('fecha_ter')
);
$this->db->insert('horario',$data);
}
$count++;
}
}
// cerramos el archivo EXCEL
$reader->close();
} else {
echo "Seleccione un tipo de Archivo Valido";
}
} else {
echo "Seleccione un Archivo EXCEL";
}
}
}