Posting Null File Input in Dataform Via Ajax

    This was actually quite annoying and was needed since the api I was given by another developer won't change it so had to go around him to achieve this. To be clear I was posting a form and inside it was a file input with some other input text values. The file input needed to always be included even if it was null...Don't ask me why.

Common Errors 
These errors can be corrected from my notes.
  1. Unexpected end of input response from wp_handle_upload
  2. Unexpected end of input

Notes

  • Create File Object
  • var f = new File([""], "filename.txt", {type: "text/plain", lastModified: date})
  • Append file to form object
    form.append("blob",blob, filename);
  • aFormData = new FormData($("form").get(0));
  • Just check the length of files property, which is a FileList
    if( document.getElementById("uploadFile").files.length == 0 ){
        console.log("no files selected");
    }
Solution
var form = $('#data');
var formData = new FormData(form);
formData.append('image', $('#frontImg')[0].files[0]);
formData.append("example", $('#amount').val());
$.ajax({
    type: 'POST',    
    url: '/api/Image',
    data: formData,
    contentType: false,
    processData: false,    
    complete: function(response) {
        alert(response);
    },
    error: function() {
        alert("ERROR!");
    }
});
Resources
  • All listed under Mozilla Docs
    • Web/API/FormData/append
    • Web/API/FormData/Using_FormData_Objects

Popular posts from this blog

Aspetcore: NLog with Postgresql

Mongodb Cheatsheet

Installing Windows on Acer chromebook 15 cb3-532