Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ollie_123's avatar

Ajax Form With File Upload

Hi All

I'm stuck on an issue where my form data isn't processing or uploading the file. When i click Submit, i get the following in the console:-

Uncaught TypeError: Failed to construct FormData: parameter 1 is not of type HTMLFormElement at $.validator.submitHandler

Please can someone advise on where i'm going wrong. i've tried a dd($request) but it doesn't output anything.

Am i going wrong with how i've written the updateOrCreate method? or is it the JS thats causing the issue?

Form:-

<div class="modal fade" id="software-modal" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="softwareModal"></h4>
            </div>
            <form id="userForm" name="userForm" class="form-horizontal" enctype="multipart/form-data">
            @csrf
            <div class="modal-body">
                <input type="hidden" name="software_id" id="software_id">
                
                <div class="form-group">
                
                        <div class="row">
                            <div class="col-sm-6">
                                <label>Operating System</label>
                                <select type="text" class="form-control" id="sw_os" name="sw_os">
                                    <option hidden>Select</option>
                                    <option>Mac</option>
                                    <option>Windows</option>
                                </select>
                            </div><!-- end col -->
                            <div class="col-sm-6">
                                <label>Type</label>
                                <select type="text" class="form-control" id="sw_type" name="sw_type">
                                    <option hidden>Select</option>
                                    <option>Master</option>
                                    <option>Slave</option>
                                </select>
                            </div><!-- end col -->
                        </div><!-- end row -->

                            <div class="padb-20"></div>
                        <div class="row">
                            <div class="col-sm-12">
                                <label>Manual</label>
                                <input type="text" class="form-control" id="sw_manual" name="sw_manual">
                            </div><!-- end col -->
                        </div><!-- end row -->

                        <div class="padb-20"></div>
                    <div class="row">
                        <div class="col-sm-12">
                            <label>Upload File</label>
                            <input type="file" name="sw_link" id="sw_link">
                        </div>
                    </div><!-- end row -->

                            <div class="padb-20"></div>
                        <div class="row">
                            <div class="col-sm-12">
                                <label>Status</label>
                                <select type="text" class="form-control" id="status" name="status">
                                    <option hidden>Select</option>
                                    <option value="Displayed">Displayed</option>
                                    <option value="Not-Displayed">Not-Displayed</option>
                                </select>
                            </div><!-- end col -->
                        </div><!-- end row -->

                </div><!-- end form-group -->
            </div><!-- end modal body -->
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary" id="btn-save" value="create">
                    Save changes
                </button>
            </div>
            </form>
        </div>
    </div>
</div>

JS:

<script>
  $(document).ready(function () {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    /*  When user click add user button */
    $('#create-new-user').click(function () {
        $('#btn-save').val("create-user");
        $('#userForm').trigger("reset");
        $('#userCrudModal').html("Add New User");
        $('#software-modal').modal('show');
    });
 
   /* When click edit user */
    $('body').on('click', '#edit-user', function () {
      var softwareEnq_id = $(this).data('id');
      $.get('softwareEnq/' + softwareEnq_id +'/edit', function (data) {
         $('#userCrudModal').html("Edit Software Details");
          $('#btn-save').val("edit-user");
          $('#software-modal').modal('show');
          $('#sw_id').val(data.id);
          $('#sw_os').val(data.sw_os);
          $('#sw_type').val(data.sw_type);
          $('#sw_manual').val(data.sw_manual);
          $('#sw_link').val(data.sw_link);
          $('#status').val(data.status);
      })
   });
   //delete user
    $('body').on('click', '.delete-user', function () 
    {
        var softwareEnq_id = $(this).data("id");
        if(confirm("Are You sure want to delete !")) 
        {
 
            $.ajax
            ({
                type: "DELETE",
                url: "{{ url('softwareEnq')}}"+'/'+softwareEnq_id,
                success: function (data) 
                {
                    $("#softwareEnq_id" + softwareEnq_id).remove();
                },
                error: function (data) 
                {
                    console.log('Error:', data);
                }
            });
        }
    });   
  });
 
 if ($("#userForm").length > 0) {
      $("#userForm").validate({
 
     submitHandler: function(form) {
 
      var actionType = $('#btn-save').val();
      $('#btn-save').html('Sending..');
      var formData = new FormData(software-modal);
      $.ajax({
          data: $('#userForm').serialize(),
          url: "{{ url('softwareEnq') }}",
          type: "POST",
          dataType: 'formData',
          cache:false,
          contentType: false,
            processData: false,
          success: function( data ) 
            {
                $('#send_form').html('Submit');
                $('#position-1-success-changelog').show(function() 
                {
                    
                var notice = new PNotify({
                    title: 'Success',
                    text: 'Software Enquiry Updated.',
                    type: 'success',
                    icon: 'fa-check-circle ',
                    addclass: 'stack-bottomleft'
                }); //end function
            }); //end response  

            console.log('form info:', data);
 
              $('#updateTable').trigger("reset");
              $('#software-modal').modal('hide');
              $('#btn-save').html('Save Changes');
                // window.location.reload();
                // setTimeout( 
                //     function() {
                //         window.location.reload(true);
                //     }, 800);
          },
          error: function (data) {
              console.log('Error:', data); // remove this for production
              $('#btn-save').html('Save Changes');
          }
      });
    }
  })
}
</script>

Controller

public function store(Request $request)
        { 
            // dd($request);
            request()->validate([
                'sw_link' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            ]);
     
            $files = $request->file('sw_link');
            $sw_link = $request->image->store('public/images');

            $softwareEnq = \App\TuningSoftware::updateOrCreate(
                ['id' => $request->sw_id],
                [
                    'sw_manual' => $request->sw_manual,
                    'sw_type' => $request->sw_type, 
                    'sw_link' => $request->sw_link,  
                    'sw_os' => $request->sw_os, 
                    'status' => $request->status
    
                ]
            );
            return Response::json($softwareEnq);
            
        }
        
        
        /**
         * Show the form for editing the specified resource.
         *
         * @param  \App\TuningSoftware 
         * @return \Illuminate\Http\Response
         */
        public function edit($id)
        {   
            $where = array('id' => $id);
            $softwareEnq  = \App\TuningSoftware::where($where)->first();
    
            return Response::json($softwareEnq);
        }

Thank you in advance.

0 likes
12 replies
ahmeddabak's avatar

Try removing this dataType: 'formData', and this var formData = new FormData(software-modal);

ollie_123's avatar

Hey @ahmeddabak. I thought that the data type had to be FormData in Jquery to parse the form data and a file to the controller?

ahmeddabak's avatar

The dataType is the data type you expect as a response from the server, it will be auto detected from jquery, plus it only accepts one of there values xml, json, script, or html like it says in the documentation jquery ajax

ollie_123's avatar

Cool thank you. So after removing that i got a 422 validation issue, i commented it out from the controller so that i can make sure that the form submits and file uploads but i'm now getting this: local.ERROR: Call to a member function store() on null

Please can you see where i'm going wrong?

public function store(Request $request)
        { 
            // dd($request);
            // request()->validate([
            //     'sw_link' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            // ]);
     
            $files = $request->file('sw_link');
            $sw_link = $request->sw_link->store('public/images');

            $softwareEnq = \App\TuningSoftware::updateOrCreate(
                ['id' => $request->sw_id],
                [
                    'sw_manual' => $request->sw_manual,
                    'sw_type' => $request->sw_type, 
                    'sw_link' => $request->sw_link,  
                    'sw_os' => $request->sw_os, 
                    'status' => $request->status
    
                ]
            );
            return Response::json($softwareEnq);
            
        }
ahmeddabak's avatar

I think you need to change there variables in the jquery ajax function to be able to upload a file

data: new FormData($('#userForm')),
type: "POST",
enctype: 'multipart/form-data',
processData: false,
ollie_123's avatar

Hey @ahmeddabak. Thanks for your response. I appreciate you helping me with this. Unfortunately though it hasn't solved it. I'm still getting Uncaught TypeError: Failed to construct FormData: parameter 1 is not of type HTMLFormElement at $.validator.submitHandler.

ahmeddabak's avatar
data: new FormData(document.getElementById('userForm')),
type: "POST",
enctype: 'multipart/form-data',
processData: false,
1 like
ollie_123's avatar

Hey @ahmeddabak that seemed to get me a step closer thank you :)

Now i'm just stuck with this error: local.ERROR: Call to a member function store() on null

which i'm guessing comes down to an issue with not being able to get the file name from the form in the controller?

public function store(Request $request)
        { 
            // dd($request->all());
            // request()->validate([
            //     'sw_link' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            // ]);
     
            $files = $request->file('sw_link');
            $sw_link = $request->sw_link->store('public/software');

            $softwareEnq = \App\TuningSoftware::updateOrCreate(
                ['id' => $request->sw_id],
                [
                    'sw_manual' => $request->sw_manual,
                    'sw_type' => $request->sw_type, 
                    'sw_link' => $request->sw_link,  
                    'sw_os' => $request->sw_os, 
                    'status' => $request->status
    
                ]
            );
            return Response::json($softwareEnq);
            
        }
jlrdw's avatar

I'm still getting Uncaught TypeError: Failed to construct FormData: parameter 1 is not of type HTMLFormElement at $.validator.submitHandler.

Between code changes, make sure you clear that browser cache. I have actually had a problem solved, but due to cache, an error would still show.

ollie_123's avatar

Thanks @jlrdw good to know for future. Unfortunately my controller is now the issue.

ollie_123's avatar

Hey @ahmeddabak, do you know what would give a 422 error on submit? I've got my CSRF Meta in the head & the X-CSRF:$ in my JS?

In the console i'm getting the given data was invalid errors: {{ "sw_link" field is required }}.

I removed the validation from the controller so that it should just process the form but still no joy. Is it because its not parsing the file in the JS / Controller?

Please or to participate in this conversation.