Upload image to folder using ajax / jquery

I'm trying to upload an image to a folder using ajax, jquery and php, but the problem is I don't know how to send the file input value to the php file when I run my code. I receive the following message:

undefined index archivo

This is my ajax call (PD. All other parameters are working correctly, I only have problems with the input file value)

function Registrar() {
      var cat = $('#cat').val();
      var nom = $('#name').val();
      var desc = $('#description').val();
      var image = $('#archivo').val(); 
     //Also tried with this, to remove the fakepath string... $('input[type=file]').val().replace(/C:\\fakepath\\/i, '') 

      $.ajax({
        url: '../../class/upload.php',
        method: 'POST',
        data: { categoria: cat, nombre: nom, descripcion: desc, archivo: image, activo: act, disponible: disp, precio: prec },
        success: function (data) {
          console.log(data);
        } 
      });
    }

      

PHP file:

<?php

    $categoria = $_POST['categoria'];
    $nombre = $_POST['nombre'];
    $descripcion = $_POST['descripcion'];
    $img = $_POST['archivo'];
    $activo = $_POST['activo'];
    $disponible = $_POST['disponible'];
    $precio = $_POST['precio'];
    $IdCategoria = 0;
    $filepath = "";

    //Imagen

    if($categoria=="Piano") {
        $IdCategoria = 1;
        $filepath = "../Files/Productos/Piano/".$img; 
    }

    $filetmp = $_FILES['archivo']['tmp_name'];
    move_uploaded_file($filetmp, $filepath);

    echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;


?>

      

And the important parts of my HTML:

<form id="registerForm" method="post" role="form" enctype="multipart/form-data" >
<input name="archivo" id="archivo" style="width: 70%;" name="textinput" class="btn btn-block" type="file" onchange="showimagepreview(this)" />

      

EDIT: showimagepreview

function showimagepreview(input) {

            if (input.files && input.files[0]) {
                var reader = new FileReader();
                reader.onload = function (e) {

                    document.getElementsByTagName("img")[0].setAttribute("src", e.target.result);
                }
                reader.readAsDataURL(input.files[0]);
            }
        }

      

How can I solve this?

+3


source to share


3 answers


Here's the solution

Html

<form id="registerForm" method="post" enctype="multipart/form-data">
    <input name="archivo" id="archivo" style="width: 70%;" class="btn btn-block" type="file" onchange="PreviewImage(this)" />
    <img id="uploadPreview" />
    <button type="submit">Submit</button>

      

Java Script



function PreviewImage() {
    var oFReader = new FileReader();
    oFReader.readAsDataURL(document.getElementById("image").files[0]);
    oFReader.onload = function (oFREvent) {
        document.getElementById("uploadPreview").src = oFREvent.target.result;
   };
};

//ajax

$("#registerForm").submit(function(event) {  
    var formData = new FormData($(this)[0]);
    if ($(this).valid()) {
        $.ajax({
            url         : '../../class/upload.php',
            type        : 'POST',
            data        : formData,
            contentType : false,
            cache       : false,
            processData : false,
            success: function(e) {alert(e)  },
            error       : function(x, t, m) {},
        });         
    }
 });

      

PHP

<?php
    echo "<pre>"; print_r($_FILES);echo "</pre>"; die; //this will show you the file transfered by form.
    $categoria = $_POST['categoria'];
    $nombre = $_POST['nombre'];
    $descripcion = $_POST['descripcion'];
    $img = $_POST['archivo'];
    $activo = $_FILES['activo'];
    $disponible = $_POST['disponible'];
    $precio = $_POST['precio'];
    $IdCategoria = 0;
    $filepath = "";

    //Imagen

    if($categoria=="Piano") {
        $IdCategoria = 1;
        $filepath = "../Files/Productos/Piano/".$img; 
    }

    $filetmp = $_FILES['archivo']['tmp_name'];
    move_uploaded_file($filetmp, $filepath);

    echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;


?>

      

+1


source


Submit your form data like this:

var formData = new FormData($("form")[0]);

$.ajax({
        url: '../../class/upload.php',
        method: 'POST',
        data: formData,
        success: function (data) {
          console.log(data);
        } 
      });

      



And you should get the file from $_FILES

, you cannot get it in $_POST

in php code.

+2


source


change this value

  $img = $_POST['archivo'];

      

to

$_FILES['archivo'];

      

Unable to access file in $_POST

+1


source







All Articles