Handling file uploads asynchronously without refreshing the page is a standard requirement for modern web applications. In WordPress, implementing secure client-side file uploads using the Fetch API combined with native PHP functions like media_handle_upload() provides a smooth user experience while maintaining security.

In this tutorial, we will walk through building a secure, custom AJAX file uploader step-by-step.

1. Creating the HTML Form and JavaScript Handler

First, add the HTML structure for your upload form to your template or shortcode:

				
					<form id="wg-file-upload-form">
    <input type="file" id="wg-file-input" name="wg_file" required />
    <button type="submit" id="wg-upload-btn">Upload File</button>
</form>
				
			

2. Enqueuing Scripts and Passing Nonces (PHP)

To execute AJAX requests securely in WordPress, we must enqueue our script and inject the AJAX URL along with a security nonce using wp_localize_script().

Add this snippet to your theme’s functions.php or custom plugin:

				
					add_action('wp_enqueue_scripts', 'wg_enqueue_file_upload_scripts');
function wg_enqueue_file_upload_scripts() {
    wp_enqueue_script(
        'wg-file-upload',
        get_template_directory_uri() . '/js/file-upload.js',
        [],
        '1.0.0',
        true
    );
    wp_localize_script('wg-file-upload', 'wgData', [
        'ajaxUrl' => admin_url('admin-ajax.php'),
        'nonce'   => wp_create_nonce('wg_file_upload_nonce')
    ]);
}
				
			

Next, place the following JavaScript logic into a dedicated file named js/file-upload.js inside your theme or plugin directory. This script intercepts the form submission, constructs a FormData object with the file payload, and sends an asynchronous POST request to WordPress via the Fetch API:

				
					document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('wg-file-upload-form');
    if (!form) return;
    form.addEventListener('submit', async function(e) {
        e.preventDefault();
        const fileInput = document.getElementById('wg-file-input');
        const statusDiv = document.getElementById('wg-upload-status');
        if (!fileInput.files.length) {
            statusDiv.textContent = 'Please select a file.';
            return;
        }
        const formData = new FormData();
        formData.append('action', 'wg_handle_file_upload');
        formData.append('wg_file', fileInput.files[0]);
        formData.append('nonce', wgData.nonce);
        statusDiv.textContent = 'Uploading...';
        try {
            const response = await fetch(wgData.ajaxUrl, {
                method: 'POST',
                body: formData
            });
            const result = await response.json();
            if (result.success) {
                statusDiv.textContent = 'File uploaded successfully! Attachment ID: ' + result.data.attachment_id;
            } else {
                statusDiv.textContent = 'Error: ' + result.data;
            }
        } catch (error) {
            statusDiv.textContent = 'An unexpected error occurred.';
            console.error('Upload Error:', error);
        }
    });
});
				
			

3. Handling the File Upload on the Server Side (PHP)

On the backend, we hook into wp_ajax_ and wp_ajax_nopriv_. We verify the security nonce, validate the user permissions or file types, and process the upload into the WordPress Media Library using media_handle_upload().

				
					// Register AJAX actions for logged-in and guest users
add_action('wp_ajax_wg_handle_file_upload', 'wg_handle_file_upload_callback');
add_action('wp_ajax_nopriv_wg_handle_file_upload', 'wg_handle_file_upload_callback');
function wg_handle_file_upload_callback() {
    // 1. Verify Nonce Security
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'wg_file_upload_nonce')) {
        wp_send_json_error('Security check failed.');
    }
    // 2. Check if file exists in the request
    if (empty($_FILES['wg_file'])) {
        wp_send_json_error('No file was uploaded.');
    }
    // Required WordPress files for handling media attachments
    require_once ABSPATH . 'wp-admin/includes/image.php';
    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/media.php';
    // 3. Process and save to Media Library
    $file_key     = 'wg_file';
    $post_id      = 0; // Set to a specific Post ID if attaching to a post
    $attachment_id = media_handle_upload($file_key, $post_id);
    // 4. Handle Upload Errors
    if (is_wp_error($attachment_id)) {
        wp_send_json_error($attachment_id->get_error_message());
    }
    // 5. Success Response
    $file_url = wp_get_attachment_url($attachment_id);
    wp_send_json_success([
        'attachment_id' => $attachment_id,
        'url'           => $file_url
    ]);
}
				
			

Key Security Best Practices

  1. Always Verify Nonces: Protect your endpoint against Cross-Site Request Forgery (CSRF) using wp_verify_nonce().
  2. Restrict File Types: Filter allowed extensions or MIME types if necessary using wp_check_filetype() before processing.
  3. Use Core Helpers: Functions like media_handle_upload() sanitize file names, move files to /wp-content/uploads/, and handle media metadata creation automatically.

Using JavaScript’s Fetch API alongside WordPress’s native media_handle_upload() allows you to build clean, asynchronous file upload interfaces without relying on external plugins or jQuery.

Be sure to check out our previous tutorials on WordPress development:
How to Create Custom ACF Gutenberg Blocks Without React
Building Custom Gutenberg Blocks Without Webpack: A Practical Dynamic Block Example
Creating Custom Admin Pages using WP_List_Table and WP_User_Query

Need help with your project? We will be happy to help with your project. Feel free to contact us. Just reach out and we will reply soon.