Wednesday, March 8, 2017

Laravel ajax show uploaded image

I have successfully uploaded a profile image, Now i want to show the uploaded/updated image instantly when upload process completes,

Jquery :

$('#profile-image-upload').change(function(e){
    var profileImageForm = $("#profileImageForm");
    profileImageForm.on('submit', function(e){
        e.preventDefault();

        var file_data = $('#profile-image-upload').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);
        console.log(form_data);
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            url: "/freelance/change-profilePic",
            data:form_data,
          dataType:'json',
          async:false,
          type:'post',
          processData: false,
          contentType: false,
          success:function(response){
            console.log(response.image);
            $('#profile-image').attr('src', response.image + '?' + new Date().getTime());
          },
        });
    }).submit();
}); 

Html img tag where it holds the profile image :

<img id="profile-image" 
     src="/uploads/freelance/profile-pics/" alt=""  class="profile-image"

     onmouseover="this.src=''"

     onmouseout="this.src='/uploads/freelance/profile-pics/'">

And the controller returns :

return Response::json(['image' => Auth::user()->profile_pic]);

Which returns e.g 1489008335.png.

I tried :

success:function(response){
   $('#profile-image').attr('src', response.image + '?' + new Date().getTime());
          },

How it can be done ?



via Gamer

Advertisement