Modern websites rely heavily on asynchronous functionality, this makes the user's experience on your site much more streamlined.
Uploading files to your server usually required the user to submit a form which refreshes the page and gives little indication of upload progress.
With jQuery's AJAX method we can asynchronously upload files to the server without having to refresh the page.
HTML
<form id="upload_form" enctype="multipart/form-data" action="uploadImage.php">
<input type="file" name="upload_in">
<button type="submit">Submit</button>
<span id="upload_notification"></span>
</form>
Here we are creating a new form "upload_form" that runs uploadImage.php on submit, we also set the encoding type to multipart/form-data as you would with a normal file upload form.
We also need a file input as well as a submit button.
The span at the bottom will just be used to notify the user about progress changes.
Javascript
$('#upload_form').submit( function( e ) {
e.preventDefault();
var formData = new FormData( $( this )[0] );
$("#upload_notification").html("Upload in progress");
$.ajax({
type : 'POST',
url : $( this ).attr('action'),
data : formData,
cache : false,
contentType : false,
processData : false,
success : function( data ){
$("#upload_notification").html( "Upload success" );
},
error : function( data ){
$( "#upload_notification" ).html( "Upload failed" );
console.log(data);
}
});
});
Here we create an event handler for the form submission, the first thing that must be done is to prevent the default action of this event ("e") by calling e.preventDefault();
Next a FormData object must be created using the the form element as a parameter, this can only be done with an element object and not a jQuery object so we must specify $(this)[0] ( $(this) is equal to $('#upload_form') at this point).
Before calling the ajax method, we can notify the user that the image upload is in progress.
Next we must call the ajax jQuery method.
The type must be set to "POST".
The url can be set to the action attribute of our form or set manually.
The data is then set to the FormData object that was created earlier.
In order to ensure no extra processing or validation is done for the file upload form, we need to make sure cache, contentType and processData is set to false. The image upload will not work without these being correctly set.
Next we create 2 handling functions, one for if the upload is successful and another for if it has failed, both will notify the user. If the upload fails it is useful to log the returned data for debugging purposes.
<?php
if( isset( $_FILES[ 'upload_in' ][ 'tmp_name' ] ) ){
// your image handling code here
}
?>
Here we create the PHP file uploadImage.php where the file should be set if you have done the process correctly.