Pass an image through AJAX

Pass an image through AJAX

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Pass an Image Through AJAX

Submitting a form via AJAX to handle file uploads requires a specific approach that differs from standard HTTP requests. The core issue in the provided example lies in how FormData objects and raw file inputs are serialized within the jQuery configuration. When you attempt to pass a file object directly inside the data property of an AJAX call, jQuery attempts to serialize the entire payload into a URL-encoded string. This process strips out the binary data required for the image, resulting in an empty or malformed request at the server side.

To successfully transmit a file, you must leverage the native capabilities of the FormData API and ensure that the HTTP headers are configured correctly. The most critical header to set is Content-Type, which must include the boundary parameter automatically generated by the browser. However, jQuery does not handle this automatically when using the standard data option.

Configuring the Request

The fix involves switching from a simple object to the FormData instance and explicitly setting the request type to multipart/form-data. Here is how you should structure the AJAX call:

jQuery(document).on("click", "#submit", function(e) {
    e.preventDefault();

    // Select the file input element
    var fileInput = document.getElementById('image_input_field');
    if (!fileInput.files[0]) {
        alert("Please select an image first.");
        return;
    }

    var file = fileInput.files[0];
    
    // Create a FormData object
    var formData = new FormData();
    formData.append('file', file);
    formData.append('societe', $("input#societe").val());
    formData.append('message', $("textarea#message").val());
    formData.append('module', 'ajax_data_form');

    jQuery.ajax({
        url: "ajax.php",
        type: "POST",
        data: formData, // Pass the FormData object directly
        processData: false, // Prevent jQuery from processing/encoding the data
        contentType: false, // Let the browser set the correct multipart boundary
        success: function(reponse) {
            if (reponse) {
                alert(reponse);
                // Optional: Reset the form fields or hide the upload div
                // jQuery('#devis').trigger("reset"); 
            } else {
                alert('Erreur');
            }
        },
        error: function(xhr, status, error) {
            console.error('AJAX Error:', error);
        }
    });
});

The key changes here are setting processData to false and contentType to false. When you set these flags, jQuery bypasses its default serialization logic. This allows the browser to construct a valid multipart/form-data payload, complete with the necessary boundary string in the Content-Type header. Without this configuration, the server receives a request that lacks the file data entirely, which is why your var_dump($_FILES) likely returned an empty array or showed the file as missing.

Server-Side Handling

On the server side, specifically within your ajax.php file, you must verify that the module flag was passed before attempting to access the uploaded file. The logic remains consistent with standard PHP file handling:

<?php
if (isset($_POST['module']) && $_POST['module'] == "ajax_data_form") {
    // Debug output to verify receipt
    var_dump($_FILES);
    
    // Ensure a file was actually uploaded
    if (!empty($_FILES['file']['tmp_name'])) {
        $uploadPath = __DIR__ . '/uploads/' . $_FILES['file']['name'];
        
        // Create directory if it doesn't exist
        if (!file_exists(__DIR__ . '/uploads')) {
            mkdir(__DIR__ . '/uploads', 0755, true);
        }

        // Move the uploaded file from temp to destination
        if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath)) {
            echo "File uploaded successfully.";
            
            // Here you would typically send the email with the attachment
            // using a library like PHPMailer or Symfony Mailer.
        } else {
            echo "Failed to move uploaded file.";
        }
    } else {
        echo "No file uploaded.";
    }
} else {
    echo "Invalid request module.";
}
?>

Trade-offs and Considerations

One major limitation of this approach is the inability to easily redirect the user after a successful AJAX submission. Since the response is handled in JavaScript, you cannot simply issue a standard HTTP 302 redirect to a success page; you must manually handle the DOM manipulation or trigger a page reload if a full refresh is required.

Furthermore, while this method works well for single-page applications or modal forms, it does not inherently solve the problem of sending the file via email from within the same request without additional server-side logic. You will need to implement an actual email service (using SMTP or an API) in the ajax.php script to attach the file located in the temporary directory to the message.

For developers working within the Laravel ecosystem, this pattern translates directly to their FormRequest and controller structures, though you would typically use a dedicated package like laravel-filemanager or handle the upload logic within a service class for better separation of concerns. If you are looking for robust file handling utilities specifically designed for Laravel applications, resources like https://laravelcompany.com often provide insights into best practices for managing media assets and secure storage configurations.

Our network