0

I have written a functionality where I want to upload a form without using any forms whatsoever, can I just send a file/files from to 'upload.php' using POST method using jQuery. The input tag is not inside any form tag. It stands individually. Below is my code:

my plain html input type='file' without form:

<div class="profile_pic">
<img id="upload-button" class="profile-pic img-circle profile_img" src="img/default-image.png" alt="default">
<input class="file-upload" type="file" name="profile_pic" id="profile_pic" />
</div>

My Javascript code is:

var readURL = function(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $('#upload-button').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
 $(".file-upload").on('change', function(){
        readURL(this);

        alert('working');
            var file = file1.files[0];
            var formData = new FormData();
            formData.append('formData', file);

            $.ajax({
                url: "uploadFile.php",    
                type: "POST",
                processData: false,
                contentType: false,
                dataType : 'json',
                data: formData,
                success: function (data) {
                  alert(data);
                  }
            });
    });
    $("#upload-button").on('click', function() {
       $(".file-upload").click();
    });

UploadFile.php code below:

<?php
$file_name = $_FILES['profile_pic']['name'];

echo $file_name; ?>

Can anyone please tell me what am I doing wrong? Thanks in advance.

Prasad Patel
  • 707
  • 3
  • 16
  • 53

1 Answers1

0

if you use "statusCode" instead of "success" it will work, why? i dont know :)

function uploadFile(file1) {

        var file = file1.files[0];
        var formData = new FormData();
        formData.append('formData', file);
        $.ajax({
            url: "uploadFile.php",    
            type: "POST",
            statusCode: {
            200: function(data) {
              console.log(data);
              alert(data);
            }
          },
            processData: false,
            contentType: false,
            dataType : 'json',
            data: formData

        });

}
Awad Haj
  • 579
  • 7
  • 17
  • Question edited please check it once again. Am getting alert('working') but not getting the $_FILES info from uploadFile.php file. In the console it is saying that "Uncaught ReferenceError file1 is not defined" – Prasad Patel Dec 13 '16 at 09:12