Due Diligence
Just to be clear I have searched for the answer to this question and found these great questions that unfortunately do not help me.
Submit form including file upload via jQuery ajax
jQuery AJAX submit form
jquery using ajax to send data and save in php
jQuery AJAX submit form
Setup
I have a system for pulling form values and posting them via ajax. A simple snippet may look something like:
// Values
var url = '/ajax/my/controller'
var values = myStuff.getFormValues($form);
// Post
$.post(url, values, function($response)
{
if ($response['status'])
{
// Success
}
else
{
// Validation error.
}
}, 'json');
My getFormValues
functions runs some custom processing to make sure I only send the information I need so I am keen on keeping it. It is probably similar to the jQuery 'serialize' function but much simpler and with custom processing.
The Problem
My get form values function basically does a $('selector').val()
to get the form values. Which does not upload the file fields. It returns a fake path like C:\fakepat\filename.png
. This of course will not work. I need to actually submit the file as part of the ajax post operation.
The question
Without switching to jquery serialize (since it doesn't fully support files anyway) and without using any other libraries such as jquery form, How do I obtain the file from the file field and post it using ajax?
Simplified, how do I simulate the behavior of a standard file field submit with an ajax post?