Upload files and data with jquery

0

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.

    
asked by Jorge Alonso 03.11.2018 в 17:47
source

1 answer

0

In your first call Ajax you already have the name and email in the superglobal $_POST so you could do:

if (move_uploaded_file($_FILES['archivo']['tmp_name'], $path)) {
    sleep(3);
    $archivo = $nombre . '.' . $ext;
    $nombre = $_POST['nombre'];
    $correo = $_POST['correo'];
    $fecha = date("Y-m-d");
    $hora = date("H:i");

    $insertar = Archivo::insertArchivo($nombre, $hora, $archivo, $fecha, $hora);
    if($insertar > 0) {
       echo $archivo;
    } else {
       echo 'error';
    }
} else {
    echo 'error';
}

In general, it would be appropriate to check if nombre and correo come in the $_POST but, in this case, they always come, only that they could be a blank string.

You could put a check such that the ajax request is sent only if it is true that:

formData.get('archivo').name.trim() !== '' &&
formData.get('nombre').trim() !== '' &&
formData.get('correo').trim() !== ''

However, , your code will now be like this (on the backend)

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);
        $archivo = $nombre . '.' . $ext;
        $nombre  = $_POST['nombre'];
        $correo  = $_POST['correo'];
        $fecha   = date('Y-m-d');
        $hora    = date('H:i');

        $insertar = Archivo::insertArchivo($nombre, $hora, $archivo, $fecha, $hora);
        if ($insertar > 0) {
            echo $archivo;
        } else {
            echo 'error';
        }
    } else {
        echo 'error';
    }

} else {
    echo 'error';
}

You have three levels of nesting and a lot of repeated code. You could rewrite the previous thing encapsulating it in a function that returns the name of the file or 'error', putting short circuits that return 'error' without having to nest:

function manejarArchivo()
{
    if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') {
        return 'error';
    }
    $ext = strtolower(pathinfo($_FILES['archivo']['name'], PATHINFO_EXTENSION));

    $nombre = uniqid();

    $path = $path . $nombre . '.' . $ext;

    if (!move_uploaded_file($_FILES['archivo']['tmp_name'], $path)) {
        return 'error';
    }

    sleep(3);
    $archivo = $nombre . '.' . $ext;
    $nombre  = $_POST['nombre'];
    $correo  = $_POST['correo'];
    $fecha   = date('Y-m-d');
    $hora    = date('H:i');

    $insertar = Archivo::insertArchivo($nombre, $hora, $archivo, $fecha, $hora);
    if ($insertar <= 0) {
        return 'error';

    }
    return $archivo;
}

echo manejarArchivo();

There you saved all else and the code is easier to understand.

    
answered by 03.11.2018 / 21:40
source