One of the most common ways to simulate upload using AJAX was to submit a form to another page which would make some validations and then save the file in the right folder or in database. Another option was to use something that worked as an intermediary between the browser and the server; some plugins (e.g. jQuery Uploadify) used to use Flash back then.
HTML5, new APIs and new possibilities
Basically, the FormData API is an interface that provides us an easy way to create sets of data and each in its own key, just like a form element with fields and values, including the INPUT[FILE] that we use to upload files!
It’s possible to create an empty FormData instance or pass to its constructor a form element which will have its fields and values copied to the new object:
// This way formData is empty var formData = new FormData(); // This way formData is filled in with the fields/values from #formElement var formData = new FormData(document.getElementById("formElement"));
It’s also possible to add new values to formData later and for such you can use the append method:
// Add more values to formData formData.append("email", "[email protected]"); formData.append("age", "20");
FormData has many other methods you can use; you can check them in the FormData documentation.
Upload using AJAX
You can check this demo of uploading file using AJAX. Below you can see its source code which uses jQuery and the FormData API. This implementation is very simple and basic but complete, so you can easily adapt it to you page.
Notes about this code:
- In case the page that receives the AJAX request is a PHP page, the form fields are accessible through the $_POST variable and the file through the $_FILES variable.
FormData is supported in the most recent browsers and you can check the compatibility table in its documentation page.
If you are implementing upload of images, you might want to check out the previous article covering Image preview before upload.