Convenience features add a certain appeal to any basic feature. An example of this, was a feature we provided for a client, who wanted a music website. A part of the requirement was an option, to allow a user to upload an audio file. This requirement was simple enough to implement, and was done easily using jQuery and Ajax. We also added an additional feature, to provide an audio preview of the file after it is uploaded. This is similar to providing an image preview, but for an audio file.
Also, the use of jQuery and Ajax allows us to upload the file, after the user has selected it, without the use of an additional upload button.
How to upload the audio file?
Let’s consider a form which provides the user an option to upload an audio file. There will be an input field to specify the audio file to be uploaded.
<input id="default_file" type="file" name="music" accept="audio/*"/>
The use of an audio tag provided in HTML5, can be made to play the audio file.
When a user selects a file to be uploaded, the change event will be triggered. Using jQuery, we handle this change event.
$('#default_file').change(function(){ //on change event formdata = new FormData(); if($(this).prop('files').length > 0) { file =$(this).prop('files')[0]; formdata.append("music", file); } });
The next step is to use ajax and to post the form, and to upload the file.
jQuery.ajax({ url: php_file_path, type: "POST", data: formdata, processData: false, contentType: false, success: function (result) { // if all is well // play the audio file } });
Upon post, the request will be sent to the server. You need to test, if the file being uploaded does not have any error, and then upload it. This will be done using php.
if ($_FILES["music"]["error"] == UPLOAD_ERR_OK) { $file = $_FILES["music"]["tmp_name"]; // now you have access to the file being uploaded //perform the upload operation. move_uploaded_file( $file, "uploads/" . $file); }
Conclusion
Thus, using AJAX and jQuery, we were able to provide an additional feature to the basic requirement. When developing features for clients, the main intention in terms of functionality, is to always provide a stable and complete solution. But we always take additional effort, and interest to add convenience features as part of the solution, to guarantee happy clients.
You may also like to read: Creating a Real Time Progress Bar using jQuery
Pankaj :
Thanks 🙂