jqueryajaxjquery-file-upload

Upload Img using ajax jquery


I would like to upload image using ajax jquery this is my view :

<form id="checkout-form" enctype="multipart/form-data">
    <input class="input-file" type="file" name="identity_id" id="identity_id">
</form>

and my jquery :

    <script>
    $('#checkout-form').on('submit', function(event){
    event.preventDefault();
    var $i = $( '#identity_id' ),
    input = $i[0].files[0];
    $.ajax({
       url:"{{ route('user.order.create') }}",
       method:"POST",
       data:{
            identity_id:input
       },
       dataType: 'json',
       contentType: false,
       cache: false,
       success:function(){

       }
     })
    })
   });
  </script>

and showing error :

Uncaught (in promise) TypeError: Failed to execute 'arrayBuffer' on 'Blob': Illegal invocation


Solution

  • Try this

    <script>
            $('#checkout-form').on('submit', function(event){
            event.preventDefault();
            var i = $( '#identity_id' ),
            var formData = new FormData();
            var input = i[0].files[0];
            formData.append('identity_id',input);
            $.ajax({
               url:"{{ route('user.order.create') }}",
               method:"POST",
               data:formData,
               contentType: false,
               cache: false,
               success:function(){
        
               }
             })
            })
           });
          </script>