I am new with Ajax I try to upload files to my folder and store the path in my MySQL, these are my advances:
I have my modal window, with which you place the data of the file:
<form class="form-horizontal" action="../../phpcrud/create_documentos.php" method="POST" id="create_documentos_form" enctype="multipart/form-data">
<div class="modal-body">
<div class="form-group">
<label for="titulo" class="col-sm-2 control-label">Titulo</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="titulo" name="titulo" placeholder="Titulo">
</div>
</div>
<div class="form-group">
<label for="archivo" class="col-sm-2 control-label">Elejir Documento</label>
<div class="col-sm-10">
<input type="file" name="archivo" id="archivo"/>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Guardar</button>
</div>
</form>
</div>
</div>
</div>
My event is called create_documentos_form, and this is the code of mi.js
$("#create_documentos_modal").on('click', function() {
$("#create_documentos_form")[0].reset();
$(".form-group").removeClass('has-error').removeClass('has-success');
$(".text-danger").remove();
$(".message_create_documentos").html("");
$("#create_documentos_form").unbind('submit').bind('submit', function()
{
$(".text-danger").remove();
var form = $(this);
var titulo = $("#titulo").val();
var file2 = document.getElementById("archivo"); //TENGO DUDA
var archivo = file2.files[0]; //TENGO DUDA
if(titulo && archivo)
{
$.ajax({
url : form.attr('action'),
type : form.attr('method'),
data : form.serialize(),
dataType : 'json',
});
}
return false;
});
});
I check that my file variable contains something with a console.log ()
Apparently there everything is fine is the name of the image, size etc, I try to store it in my Php file as follows:
if($_POST) {
$validator = array('success' => false, 'message_create_documentos' => array());
$titulo = $_POST['titulo'];
$nombre = $_FILES['archivo']['name'];
$tipo = $_FILES['archivo']['type'];
$tamanio = $_FILES['archivo']['size'];
$ruta = $_FILES['archivo']['tmp_name'];
$destino = "archivos/" . $nombre;
$sql = "INSERT INTO documentos (titulo,ruta) VALUES ('$titulo', '$destino')";
$query = $connect->query($sql);
if($query === TRUE) {
$validator['success'] = true;
$validator['message_create_documentos'] = "Agregado Exitosamente";
} else {
$validator['success'] = false;
$validator['message_create_documentos'] = "Error mientras agrega la información";
}
$connect->close();
echo json_encode($validator);
}
This part is where the record is lost