I have the following form:
<form class="formuploadajax" method="post" enctype="multipart/form-data">
<input type="text" id="nombre" name="nombre" placeholder="Escribe tu nombre">
<br>
<input type="email" id="correo" name="correo" placeholder="Escribe tu correo electronico"/>
<br>
<input type="file" id="archivo" name="archivo"/>
<br>
<input type="button" value="Subir archivos" onClick="subirArchivo();"/>
</form>
And I have the following scripts:
function subirArchivo()
{
var formData = new FormData($(".formuploadajax")[0]);
$.ajax({
url: '../includes/upload_archivo.php',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
$(".cargar-archivo").show();
$(".cargar-archivo").html("<img src='../img/ajax-loader.gif'>");
},
success: function(data){
if(data != "error")
{
$(".form-tarea").hide();
registrarArchivo(data);
}
else
{
$(".cargar-archivo").hide();
vex.dialog.alert("Error al subir archivo, intenta de nuevo");
}
}
});
}
function registrarArchivo(archivo)
{
var nombre = $("#nombre").val();
var correo = $("#correo").val();
$.ajax({
type: "POST",
url: "../includes/acciones/archivos/insert_archivo.php",
data: "nombre=" + nombre + "&correo=" + correo + "&archivo=" + archivo,
success: function(data)
{
if(data == 1)
$(".cargar-archivo").html(archivo);
else
{
$(".cargar-archivo").hide();
vex.dialog.alert("Error al subir archivo, intenta de nuevo");
}
}
});
}
upload_archive.php
<?php
$path = '../archivos/';
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
$ext = strtolower(pathinfo($_FILES['archivo']['name'], PATHINFO_EXTENSION));
$nombre = uniqid();
$path = $path.$nombre.".".$ext;
if (move_uploaded_file($_FILES['archivo']['tmp_name'], $path))
{
sleep(3);
echo $nombre.".".$ext;
}
else
echo "error";
}else{
echo "error";
}
?>
insert_archive.php
<?php
include_once("../clases/class.Archivo.php");
extract($_POST);
# nombre
# correo
# archivo
date_default_timezone_set('America/Mexico_City');
$fecha = date("Y-m-d");
$hora = date("H:i");
$insertar = Archivo::insertArchivo($nombre, $hora, $archivo, $fecha, $hora);
if($insertar > 0)
echo 1;
else
echo 0;
?>
What I have to do here is upload a file to the server and the name of that file along with the name and mail data saved in a database.
As you can see, I am using the FormData object to send the file to php and upload it to the server, but if you see the first run the file upload method () what is the file uploading me, if the file was uploaded correctly I executed The file-record method () that is the one registers the information in the database.
The question is, is this what I'm doing right? As I have it if it works but I have the doubt if in a single method I can send to php both the file to upload and the data that must be saved in the database, instead of two methods.