Search code examples
ajaxlaravelform-data

Uncaught TypeError: FormData constructor: Argument 1 does not implement interface HTMLFormElement. in laravel


My form is like this demo

resume

Q.1 I would like to convert this form to ajax but it seems like my ajax code lacks something. On submit doesn't do anything at all.

Q2. I also want the function to fire on change when the file has been selected not to wait for a submit.

Q3. I want to when I clicked on Next step button. The all of form save And go to next page.

My blade

<form method="post" enctype="multipart/form-data" action="{{ route('update', auth()->id()) }}">
    @csrf
    @method('put')
    <fieldset>
        @include('Home.steps.step-1')
    </fieldset>
    <fieldset>
        @include('Home.steps.step-2')
    </fieldset>
    <fieldset>
        @include('Home.steps.step-3')
    </fieldset>
    <fieldset>
        @include('Home.steps.step-4')
    </fieldset>
    <fieldset>
        @include('Home.steps.step-5')
    </fieldset>
    <fieldset>
        @include('Home.steps.step-6')
    </fieldset>
</form>

js

$(document).ready(function (e) {
    $('.btn-next').on('click',(function(e) {
        e.preventDefault();
        var formData = new FormData(this);

        $.ajax({
            type:'POST',
            url: $(this).attr("{{ route('update', auth()->id()) }}"),
            data:formData,
            cache:false,
            contentType: false,
            processData: false,
            success:function(data){
                console.log("success");
                console.log(data);
            },
            error: function(data){
                console.log("error");
                console.log(data);
            }
        });
    }));
});

I get this error in console.

error

Uncaught TypeError: FormData constructor: Argument 1 does not implement interface HTMLFormElement.


Solution

  • You need to give form element not button

    var formData = new FormData($('#form-id'));