Posting a form with file attachments using pjax (and jQuery.form?)
jquery, pjax
Solution
It seems like you may need to use a `FormData` object in your AJAX/pJAX request which can process files. You can read more on the Mozilla Developer Network.
For example, if this is your form:
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
First get the file contents like so:
var formData = new FormData($('form')[0]);
Then you could use a jQuery `$.ajax` request or a simple `XMLHttpRequest();` like so:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://foo.com/processfile.php");
xhr.send(formData);
Or similarly in jQuery:
$.ajax({
url: 'http://foo.com/processfile.php',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false
});
On the server side, in `processfile.php`, you can receive/display the file contents with:
`$file = $_FILES['file']['name'];`
This should work with pJAX as it is asynchronous! Just make sure you place this request BEFORE your pJAX request, or if you're using jQuery, you can add it as part of the success callback. For example (without knowing which pJAX library you are using):
$.ajax({
url: 'http://foo.com/processfile.php',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
$.pjax({url: url, container: '#pjax-container'});
}
});
Edit: If you would like to support IE7+, you need to fallback to using a hidden iframe element for the upload as FormData is only supported in Internet Explorer 10. A great plugin for submitting files which I have tested and works without jQuery is http://fineuploader.com/ which in my opinion is better/easier to use than the https://github.com/malsup/form (jquery.form plugin).
Problem
I successfully use pjax for links and forms (`GET` as well as `POST`). But now I have a form which also has to send an `<input type="file"...>`. Since pjax does not support this, I had a look at https://github.com/malsup/form (jquery.form plugin) which does support submitting form data with files, but not in the "pjax" way of working with browser history objects. So, how would it be possible to use pjax functionality with forms that contain file fields? Any ideas? Edit: The reason why I do not simply use FormData objects, but the jquery.form plugin: Internet Explorer can not handle them. And the plugin has a workaround for this browser. I do not insist of using jquery.form plugin, but I need a way to make it work with all the major browsers.