1

I'm trying to make an image uploader with php and jquery but i can't get it to work.
My question is
Why is $_FILES['image']; empty?
Heres my code

Html
index.php

 <form id="uploadForm" action="" method="post">
 <input name="image" type="file" id="image" />
 <a href="#" id="uploadforms">Upload</a>
 </form>
 <div id="uploadresult"></div>

jQuery
javascript.js

  function uploadimages(){
   $.ajax({
      type: 'POST',
      url: '../ajax/upload.php',
      processData: false,
      contentType: false,
      cache: false,
      data: new FormData(this),
       success: function (data) {
         $("#uploadresult").html(data);
       },
    });
  }
  $("#uploadforms").click(function(){
    uploadimages();
  });

Php
Upload.php

 <?php
 if(!empty($_FILES['image'])) {
     echo "Upload image";
 }
 else{
     echo "Error";
 }
 ?>
Rabbit
  • 127
  • 1
  • 14

1 Answers1

3

You forgot enctype='multipart/form-data' in your form like this

 <form id="uploadForm" action="" method="post" enctype="multipart/form-data">

For more info click here and here

Update:

Pass form from function call

 $("#uploadforms").click(function(){
    var form = $('form')[0]; //access form obj
    uploadimages(form);
  });

And access it in function as

function uploadimages(formObj){
   $.ajax({
      type: 'POST',
      url: '../ajax/upload.php',
      processData: false,
      contentType: false,
      cache: false,
      data: new FormData(formObj), //changes here
       success: function (data) {
         $("#uploadresult").html(data);
       },
    });
  }
Community
  • 1
  • 1
Nabin Kunwar
  • 1,965
  • 14
  • 29