File Upload Using jQuery Ajax

AJAX stands for Asynchronous JavaScript and XML. Using AJAX we can make HTTP request to the web server through JavaScript. It uses the browser built-in XMLHttpRequest object to make the request.

jQuery is most used JavaScript library makes the AJAX request even easier. We can make both GET and POST request using AJAX. And can send and receive data in different format like JSON, HTML, XML and text.

In this article I am going to show a simple method to upload file using jQuery Ajax.
First create your HTML file and include jQuery.

Use below sample form


<form onsubmit=”return process_form(this);”>
<input type=”text” id=” file_title” name=”file_title” />
<input type=”file” id=”files” name=”files” multiple=”” />
<input type=”submit” value=”Submit” />
</form>

Use below JavaScript to process the form.


function process_form(form) {
//Setting up post data
var data = new FormData();
data.append('file_title', $('#file_title').val());
for (var k in jQuery('#files').prop('files')) {
                data.append('file' + k, $('#files').prop('files')[k]);
}
//calling ajax file upload function
request_ajax_file(‘upload.php’, data, process_form_callback);
return false;
}

function process_form_callback(response) {
//Callback from server
}

This is the function that makes AJAX request with files.


function request_ajax_file(ajax_url, ajax_data, ajax_callback) {
    jQuery.ajax({
        url: ajax_url,
        data: ajax_data,
        type: 'POST',
        processData: false,
        contentType: false,
        success: function (response) {
            if (typeof ajax_callback == 'function') {
                ajax_callback(response);
            } else if (typeof ajax_callback == 'string') {
                if (ajax_callback != '') {
                    eval(ajax_callback + '(response)');
                }
            }
        }
    });
}

The post and files data can be processed in PHP.

Hope this helped.

Share this Post