skip to Main Content

In my project, all forms are similar to each other, so I want to write one click function to run all.

Following code works fine except files. File value outputs as undefined. How can I attach file to this form data?

Here’s my click function:

$("#save_form").click(
    function(event){
        event.preventDefault();

        var formData = {};

        $('.form-value').each(function() {
            var id = $(this).attr('id');
            var value;
            if ($(this).is('select')) {
                value = $(this).find('option:selected').val();
            } else if ($(this).is(':file')) {
                value = $(this)[0].files[0].value; // Returns undefined.
            } else {
                value = $(this).val();
            }
            formData[id] = value;
        });

        console.log(formData);

When I use without value:

value = $(this)[0].files[0]

I get:

Uncaught TypeError: Illegal invocation

2

Answers


  1. Chosen as BEST ANSWER

    With the help of David and Unmitigated, I solved the issue.

    • I send file, not the value.

      value = $(this)[0].files[0];
      
    • And than, I added two lines to ajax (processData and contentType as false)

      method: 'POST',
      data: formData,
      processData: false, 
      contentType: false,
      

  2. Just use the file itself. Files do not have a value property.

    value = this.files[0];
    

    To send the FormData with jQuery.ajax, add the options processData: false and contentType: false to prevent jQuery from trying to convert the FormData.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search