0

I am using ajax to upload a photo in Laravel. URL is working fine but data is not receiving in function in a controller.

HTML Code

<input type="file" id="photo_input">

Ajax / JQuery Code

$('#photo_input').change(function(){
var formData = new FormData('#photo_input');    
$.ajax({
       type:'POST',
       url: home_url+'/upload-image',
       data:formData,
       cache:false,
       enctype: 'multipart/form-data',
       contentType: false,
       processData: false,
       success:function(data){
               console.log("success");
                console.log(data);
            },
            error: function(data){
                console.log("error");
                console.log(data);
            }
        });
    });


PHP Code in Controller

public function uploadImage(){
  $data = Input::all();
  print_r($data);
}


Response from function in a controller

array(
);

I haven't used <form> tag in html, I want to upload it directly. Do I need to add <form> tag? Is there anything which is missing?

Omkar
  • 298
  • 5
  • 27

2 Answers2

1
$("#example-form").submit(function(){

var formData = new FormData($(this)[0]);
    $.ajax({
        data: formData
    });
});
milo526
  • 5,012
  • 5
  • 41
  • 60
syntaxe
  • 112
  • 4
  • @milo Thanks for answering but I am not using
    so can you please suggest how do I upload file without using
    tag (if possible)?
    – Omkar Aug 16 '17 at 19:22
  • You can use base64, post base64 data with ajax; https://stackoverflow.com/a/36281449/2693988 Later use PHP to image method; https://stackoverflow.com/a/15153931/2693988 – syntaxe Aug 17 '17 at 08:43
0

Do it like this:

<form method="POST" id="photoform" enctype="multipart/form-data">
<input type="file" id="photo_input">
</form>

And accordingly ajax request should change like this:

$('#photoform').submit(function(){
var fileupload = $('#photo_input').val();    
$.ajax({
       type:'POST',
       url: home_url+'/upload-image',
       data:{
           file: fileupload,
       },
       cache:false,
       enctype: 'multipart/form-data',
       contentType: false,
       processData: false,
       success:function(data){
               console.log("success");
                console.log(data);
            },
            error: function(data){
                console.log("error");
                console.log(data);
            }
        });
    });
Haider Ali
  • 1,081
  • 8
  • 23
  • You can also do it without form as discussed in this url https://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously – Haider Ali Aug 15 '17 at 10:37
  • Your code wont work because this is not a way to upload a file using ajax. You will have to use formdata to upload files. – Farsay Aug 15 '17 at 12:12
  • @Farsay it will definitely work. I have used it in such way. – Haider Ali Aug 16 '17 at 03:31