4

Hi Friends,
I am trying to upload an image using ajax in laravel 5.4

Issue :
Formdata is empty on server-side

CODE :

View :

<form role="form" action="{{route('auth.upload')}}" method="post" enctype="multipart/form-data" id="form3">
     {{ csrf_field() }}
     <h3>Upload Logo</h3>

     <div class="form-group">
          <label class="custom-file upload-image">
          <input type="file" id="image" name="image" class="custom-file-input">
          <span class="custom-file-control"></span>
          </label>
      </div>
      <button type="submit" class="btn btn-upload">Save Image</button>
</form>  

JS :

$('#form3').on('submit',function(e){
    e.preventDefault();

    var url = $(this).attr('action'),
    post = $(this).attr('method'),
    data = new FormData(this);

    $.ajax({
        url: url,
        method: post,
        data: data,
        success: function(data){
            console.log(data);
        },
        error: function(xhr, status, error){
            alert(xhr.responseText);
        },
        processData: false,
        contentType: false
    });
});  

Route :

Route::post('home/form3', 'HomeController@store')->name('auth.upload');  

Controller :

public function store(Request $request){
    if ($request->ajax()) {

        return $request->all(); // THIS IS RETURNING EMPTY OBJECT

        if ($request->hasFile('image')) {

            $name = $request->image->getClientOriginalName();
            $request->image->storeAs('public/upload',$name);

            $company = new Company;
            $url = Storage::url($name);
            $company->update(['image'=>$url]);

            return response(['msg'=>'image uploaded']);
        }else{
            return response(['msg'=>'No file has selected']);
        } 
    }
}  

return response from server side is :

Object {_token: "zFKgoBkdjaIswMG5X0fOyVtaGSYMs84iPDtJA4F5", image: Object}
   image : Object
   _token : "zFKgoBkdjaIswMG5X0fOyVtaGSYMs84iPDtJA4F5"
   __proto__ : Object  

I can see only token is returning but not data of uploaded image. If I submit form without using ajax then it is working fine.

Output if submitted without using ajax (this is the output I am expecting even submitted using ajax):

array:2 [▼
  "_token" => "eVEjl9UW4rU69oz1lIIiuNABZVpRJFldDST02Nje"
  "image" => UploadedFile {#229 ▼
    -test: false
    -originalName: "empty-normal.png"
    -mimeType: "image/png"
    -size: 85494
    -error: 0
    #hashName: null
    path: "C:\xampp\tmp"
    filename: "php917E.tmp"
    basename: "php917E.tmp"
    pathname: "C:\xampp\tmp\php917E.tmp"
    extension: "tmp"
    realPath: "C:\xampp\tmp\php917E.tmp"
    aTime: 2017-05-18 11:17:11
    mTime: 2017-05-18 11:17:11
    cTime: 2017-05-18 11:17:11
    inode: 0
    size: 85494
    perms: 0100666
    owner: 0
    group: 0
    type: "file"
    writable: true
    readable: true
    executable: false
    file: true
    dir: false
    link: false
    linkTarget: "C:\xampp\tmp\php917E.tmp"

} ]

Can any one help me in solving this issue ?

**THANKS IN ADVANCE...

Himakar
  • 345
  • 4
  • 17
  • Please check data which is returning from FormData function, log that into console and see if its logging there. – Bhaumik Pandhi May 18 '17 at 11:27
  • @PandhiBhaumik Thanks for your comment. By using console log we can not inspect formdata. If we do so it will return empty object. Here is more explanation on inspecting formdata [link](http://stackoverflow.com/questions/17066875/how-to-inspect-formdata). I found no error from client side script. – Himakar May 18 '17 at 11:43
  • So, I was right problem with client side? – Bhaumik Pandhi May 18 '17 at 11:46
  • @PandhiBhaumik No problem with client side – Himakar May 18 '17 at 11:49
  • Please check data using `dd($request->all())` and see if you can get data there. – Bhaumik Pandhi May 18 '17 at 11:53
  • @PandhiBhaumik I tried it too. Both gives same output (EMPTY formdata and token). – Himakar May 18 '17 at 12:01
  • Nothing wrong in ajax part, your ajax part is working fine with my code – Dinesh Kumar May 18 '17 at 13:42
  • @Nobita Thankyou, so have you checked with the view code of mine and are you using laravel backend ? or anything else ? Can you please show your code. You can contact me on whatsapp (+91 9901929792) or line (lineID : suhittrahimakar) or facebook (himakar pv). – Himakar May 18 '17 at 14:06
  • I checked with codeigniter with the view and js – Dinesh Kumar May 18 '17 at 14:12

1 Answers1

0

Try this, it will help you.

$(document).on('submit', 'yourformId', function (event) {
    event.stopPropagation();
    event.preventDefault();
    var data = new FormData($(this)[0]);


    if (xhr && xhr.readyState !== 400 && xhr.status !== 200) {
        xhr.abort();
    }

    var xhr = $.ajax({
        url: "urltoUpload",
        method: "POST",
        cache: false,
        data: data,
        contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
        processData: false, // NEEDED, DON'T OMIT THIS
        // dataType: 'json',
        statusCode: {
            404: function () {
                alert("status message")
            },
            500: function () {
                alert("server down");
            }
        },
        beforeSend: function (jqXHR, setting) {
            if (setting.status !== 200) {
                console.log("You can put here")
            }
        },
        error: function (jaXHR, textStatus, errorThrown) {
            // Now it will get parse error because dataType is json and response is html
            // console.log(errorThrown);
        },
        success: function (data, textStatus, jqXHR) {
            console.log(data);

            if (typeof data.error === 'undefined') {
                // Success so call function to process the form
                console.log('SUCCESS: ' + data.success);
            }
            else {
                // Handle errors here
                console.log('ERRORS: ' + data.error);
            }
        },
        complete: function (jqXHE, textStatus) {
            document.body.innerHTML = "dfafsaf";
        }

    });
});

In you controller you can use

dd($request->all());

for your sure !!

François Maturel
  • 5,884
  • 6
  • 45
  • 50