Code Bug Fix: Upload file audio without refresh page on Laravel and Ajax Jquery

Original Source Link

i found a problem when upload audio file with ajax

<form enctype="multipart/form-data" id="voiceformpost" method="POST">
  @csrf
  <input name="file" type="file" accept="audio/*" capture="microphone" id="recorder">
  <input type="text" name="post_id" hidden="hidden" value="{{$logid}}">
</form>

and this is the jquery script:

<script>
    $('#recorder').on('change', function(){
        var form      = $("#voiceformpost");
        var file_data = $("#recorder").prop("files")[0];   
        var formdata  = new FormData(form);
        formdata.append('file', file_data);
        $.ajax({
            url : "{{url('store-voice')}}",
            type: "POST",
            data : formdata,
            processData: false,
            contentType: false,
            success:function(data){
            }
        });
    });

</script>

error on console
“TypeError: FormData constructor: Argument 1 does not implement interface HTMLFormElement.”

you can simply remove <form> tag and add on change listener to your input

$(document).ready(function() {
        $('#recorder').on('change', uploadFile);
    })

and in uploadFile function you can accept data

    function uploadFile(event) {
        var files = event.target.files;
        var formdata = new FormData();

        $.each(files, function(key, value) {
            formdata.append(key, value);

        });
    }

Tagged : / /

Leave a Reply

Your email address will not be published. Required fields are marked *