0

I'm trying to submit a form with file upload but the data gets inserted into the table but with the file the error that I encounter says

Message: Undefined index: user_file

Below is my code.

HTML:

 <form id="create" method="post" action="" enctype="multipart/form-data" class="form-horizontal form-label-left">
<input type="text">
....
<input type="file" name="user_file" id="user_file"/>
<button type="submit" class="btn btn-primary" name="save" id="save">Save</button>

JS:

$("#create").submit(function(e) {

e.preventDefault(); 

var form = $(this);
.ajax({
       type: "POST",
       url: url,
       data: form.serialize(), 
      success: function(data)
       {
        if(data.status === 'success')
        { 
          //success
        } 
        else 
        { 
          //error
        }
        $("#create")[0].reset();
       }
     });
 });

I tried the existing online but could not fix this issue.

Thanks in advance.

Edit: The solution suggested did not solve my problem as I'm facing this issue only when the file input is part of a form where other input types are present.

However the solution suggested has only the input type file and that is not my issue.

Krish
  • 401
  • 6
  • 18
  • Possible duplicate of [How can I upload files asynchronously?](https://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously) – Alex Jul 03 '19 at 19:12
  • @Alex no this is not my solution. I have edited my question to explain the same. – Krish Jul 04 '19 at 08:54

1 Answers1

0

You can try this.

$("#create").submit(function(e) {

    e.preventDefault(); 

    var form = $(this);
    .ajax({
           type: "POST",
           url: url,
           data: new FormData(this), 
           processData: false,
           contentType: false,
          success: function(data)
           {
            if(data.status === 'success')
            { 
              //success
            } 
            else 
            { 
              //error
            }
            $("#create")[0].reset();
           }
         });
     });
Gaurang Ghinaiya
  • 559
  • 9
  • 26