3

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

undefined index archivo

This is my ajax call (PD. All the other parameters works properly, I only have problems with the file input 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?

4
  • Possible duplicate: stackoverflow.com/questions/23980733/… Commented Jul 6, 2017 at 3:37
  • can you show your "showFilePreview" function? That may have the solution for you need. Does it use FileReader? Commented Jul 6, 2017 at 3:40
  • @GarrGodfrey Yes, I use FileReader, I added that code to my post. Commented Jul 6, 2017 at 3:44
  • @AbdulRafay I'm trying using that code and now I don't get any error message, but now seems that my function is not executed, when I submit the form my page its only reloaded Commented Jul 6, 2017 at 3:57

3 Answers 3

2

Send 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 have to get the file with $_FILES, you can not get it in $_POST in php code.

Sign up to request clarification or add additional context in comments.

6 Comments

And what should I put on $_POST[' '] sending data in that way? The name of my inputs?
You put your input name attributes as keys in $_POST[];
I have the problem mentioned above... now I dont get any error message but now my page only is reloaded, doesn't show my echo line
The piece of code I wrote above is to be placed with your ajax function.
I need to replace my ajax code with your code right?
|
1

Here is you 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 Comment

Same issue here, doesn't print the echo lines. just reloads the page
1

change this

  $img = $_POST['archivo'];

to

$_FILES['archivo'];

Files object cannot be recieved in $_POST

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.