recepduman's avatar

Ajax post with image in laravel ?

Hello,

I would like to use image uploading with Ajax post. My codes are as follows;

<input type="file" id="file" data-size="sm" data-badge="false" data-iconName="glyphicon-inbox" data-buttonName="btn-primary" name="receipt">
$.ajax({
      url: '',
      type: "post",
      data: {'_token': '{{ csrf_token() }}','receipt':$('#file').val()}
    });
$receipt = $request->file('receipt');
$fileName = $receipt->getClientOriginalName();
$fileExtension = $receipt->getClientOriginalExtension();
$name = str_slug($fileName) . str_slug(str_random(5)) . '.' . $fileExtension;
$move = $receipt->move('Backend/avatar/',$name);
$ex->receipt = $name;
 $ex->save();

But, I am getting this error;

Call to a member function getClientOriginalName() on null

I have a lot of inputs. The form is like Personal Info. I have to use my codes like that. How can I solve this ?

0 likes
5 replies
sylar's avatar

Why not ? I'm not familiar with vuejs but i guess u can send formdata object through $http.post or something like this in (vuejs world)

kaytcat's avatar

I got it working by using the new html5 ajax formData object and then in my ajax request setting the processData and contentType to false like so: (Note this will only work ie10+)

var submitAjaxRequest = function(e) {
    var formData = new FormData(this);
    $.ajax({
                type: POST,
                url: "",
                data: formData,
                processData: false,
                contentType: false,
                success: function() {},
            });
};
$('form[data-remote]').on('submit', submitAjaxRequest);

Please or to participate in this conversation.