How to preview an image before and after upload?

How to preview an image before and after upload?

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

Stefan Bogdanescu

Founder & Senior Architect

Why Image Previews Fail and How to Fix Them

The provided code snippet demonstrates a common pattern for handling file uploads: an <input type="file"> element paired with a hidden or visible <img> tag intended to display the selected file. However, the preview logic relies on AjaxUpload, a third-party library that is no longer maintained and introduces significant friction when integrating modern event listeners.

The primary reason the preview does not work in your specific case lies in the mismatch between how AjaxUpload triggers its events and how jQuery handles them. In the script provided, you are attempting to access the form's action URL inside the onSubmit callback using $('newHotnessForm').attr('action'). At the moment the file is selected but not yet submitted, the DOM element with the ID newHotnessForm exists, but the AJAX library often intercepts the native form submission. If your form relies on standard HTML attributes to determine where the data goes, you are likely fighting against an asynchronous flow that expects a server endpoint different from the one currently configured.

Furthermore, the logic inside onComplete attempts to load the image using thumb.load(). This method is asynchronous and triggers a callback only after the image has fully downloaded. While your code correctly removes the 'loading' class in that callback, it creates a race condition. If you rely on visual feedback (like a spinner) to indicate status, the user might see the loading state persist or flicker because the load event fires independently of the AJAX response parsing.

To resolve these issues without relying on deprecated libraries like AjaxUpload, you can leverage the native File API and the Fetch API, which are supported in all modern browsers and require no external dependencies. This approach gives you direct control over the upload lifecycle and error handling.

Here is a robust implementation that replaces the custom plugin with vanilla JavaScript:

<form action="/upload" method="post" enctype="multipart/form-data" id="newHotnessForm">
    <label for="image">Upload Image:</label>
    <input type="file" id="imageUpload" name="image">
    <button type="submit" class="button">Save</button>
    
    <div id="preview-container">
        <!-- Start with a placeholder or empty src -->
        <img width="160px" height="120px" src="" alt="Preview" id="thumb">
    </div>
</form>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const fileInput = document.getElementById('imageUpload');
    const thumbImg = document.getElementById('thumb');
    const form = document.getElementById('newHotnessForm');
    const previewContainer = document.getElementById('preview-container');

    // Handle file selection to show local preview immediately
    fileInput.addEventListener('change', function (event) {
        const file = event.target.files[0];
        
        if (!file) return;

        // Create a temporary URL for the file object
        const fileURL = URL.createObjectURL(file);
        thumbImg.src = fileURL;

        // Optional: Add a visual indicator that the user has selected a file
        previewContainer.style.opacity = '1';
    });

    // Handle form submission
    form.addEventListener('submit', function (event) {
        event.preventDefault(); // Prevent default redirect to handle upload manually
        
        const formData = new FormData(form);
        
        // In a real-world scenario, you would use fetch() or XMLHttpRequest here
        // to send the file to your PHP endpoint.
        console.log('Uploading file:', formData.get('image'));

        // Reset form after successful upload logic
        form.reset();
        thumbImg.src = '';
    });
});
</script>

Handling the Upload Destination

Your second question concerns linking the saved photo to another PHP page. When you click "Save," the standard behavior of an HTML form is a full page redirect to the URL specified in the action attribute. If your server-side script processes the upload and then redirects, ensure that the target URL includes the necessary parameters or query strings if the subsequent page needs to display the image immediately.

For example, if your PHP handler at /upload.php processes the file and saves it to a database with an ID of 123, you might redirect as follows:
header("Location: /profile.php?id=123");

If you prefer not to use a server-side redirect, you can intercept the submission using JavaScript (as shown in the code block above), send the file via fetch() or XMLHttpRequest, and then update the page location manually only after receiving a success signal from the server. This gives you granular control over the user experience, such as showing a confirmation message before navigating to the next page.

Best Practices for Image Handling

When implementing image uploads, always validate the file type on the client side using the accept attribute (e.g., accept="image/*") and check the MIME type in your PHP script server-side. Never trust the client alone, as users can manually modify the file extension before uploading. Additionally, ensure that the enctype="multipart/form-data" is present on the form tag; without it, the file data will not be parsed correctly by your PHP endpoint.

If you are working within a Laravel ecosystem, consider using the intervention/image package to generate thumbnails automatically upon upload, ensuring consistent dimensions regardless of the source file size. This prevents layout shifts when images load and ensures that the preview element matches the stored dimensions exactly.

Our network