Question

I have the following HTML form:

<form action="https://portal.    .com/index.php/ajax/do_add" method="post" accept-charset="utf-8" id="add_form" enctype="multipart/form-data"><div style="display:none">
 <input type="hidden" name="csrf_test_name" value="    " />
  <table id="table_add">        
   <tr>
    <td>Type:</td>
    <td><select name="type">
     <option value="blank"></option>
     <option value="document">Document</option>
     <option value="software">Software</option>
     <option value="video">Video</option>
    </select></td>
   </tr>

   <tr class="add_doc add_sw"><td>File:</td><td><input type="file" name="file" /></td></tr>
   <tr class="add_vid"><td>URL:</td><td><input type="text" name="url" value=""  /></td></tr>
   <tr class="add_doc"><td>Title:</td><td><input type="text" name="title" value=""  /></td></tr> 
    <!--OTHER ELEMENTS REMOVED FOR BREVITY -->
   <tr class="add_doc add_sw add_vid"><td colspan="2"><input type="submit" name="submit" value="Submit"  /></td></tr>
  </table>
 </form>

I have the following jQuery code (note that $ml is equal to the default $):

$ml('form#add_form')
.submit(function(e){
    e.preventDefault();
    console.log($ml(this)); //outputs the form element context, as I was expecting
    var formdata = new FormData($ml(this));

    $ml.ajax({
        type: "POST",
        url: "/ajax/do_add",
        data: formdata,
        processData: false,
        contentType: false
    })
    .done(function(msg) {
        $ml('form#add_form').each(function(){ this.reset();});
        $ml('td#form_add_status').html('<span style="color:green;">Update complete</span>');
    })
    .fail(function(jqXHR, msg) {
        $ml('td#form_add_status').html('<span style="color:red;">Error Updating Entry: ' + msg + '</span>');
    })
 });

Without using FormData and just manually passing the form info it works -- Except that I have a file type input. Without AJAX the form works fine, with AJAX I need FormData to pass the file. I've scoured the web and have found several things but none have worked.

The developer console shows the following when being sent:

Debug Info

Was it helpful?

Solution

I'm not 100% sure, but according to docs FormData accepts an HTMLFormElement which may not be acceptable wrapped in a jQuery object ($ml(this)). Try passing just this?

The other alternative is to use the tried-and-true $(this).serialize() instead of introducing FormData.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top