Enhancing Image Upload with Ajax/JavaScript: Generating Multiple Previews

I've been experimenting with an Ajax image uploader that I found on this website. Currently, I have managed to create duplicate preview images: one displayed under the input field and the other elsewhere on the page labeled as "this what you chose". However, a problem arises when the user selects a file, changes their selection, and ends up with both old and new images being displayed in the yourCustomPreview.

Is there a way to only show the most recent preview picture without the previous one lingering? For more clarity, please refer to the source files here

uploaderPreviewer.js- Original function

<script>
function displayImage($previewDiv, imageUrl) {

    var imageFilename = imageUrl.substr(imageUrl.lastIndexOf('/') + 1);

    $previewDiv
        .removeClass('loading')
        .addClass('imageLoaded')
        .find('img')
        .attr('src', imageUrl)
        .show();
    $previewDiv
        .parents('table:first')
        .find('input:hidden.currentUploadedFilename')
        .val(imageFilename)
        .addClass('imageLoaded');
    $previewDiv
        .parents('table:first')
        .find('button.removeImage')
        .show();
}
</script>

uploaderPreviewer.js- Modified function

<script>
    function displayImage($previewDiv, imageUrl) {
    //New
    var yourCustomPreview = $('#custompreview');

    var imageFilename = imageUrl.substr(imageUrl.lastIndexOf('/') + 1);

    $previewDiv
        .removeClass('loading')
        .addClass('imageLoaded')
        .find('img')
        .attr('src', imageUrl)
        .show();
    $previewDiv
        .parents('table:first')
        .find('input:hidden.currentUploadedFilename')
        .val(imageFilename)
        .addClass('imageLoaded');
    $previewDiv
        .parents('table:first')
        .find('button.removeImage')
        .show();

        //New
        yourCustomPreview.append('<img src="' + imageUrl + '"/>');

    }
</script>

Answer №1

Alright, give this a shot:

MODIFY AS FOLLOWS:

substitute the displayImage function with the following code snippet:

function displayImage($previewDiv, imageUrl) {
    //New
    var yourCustomPreview = $('#custompreview');
    var imageId = $($previewDiv.context).attr('id');
    var imageFilename = imageUrl.substr(imageUrl.lastIndexOf('/') + 1);

    $previewDiv
        .removeClass('loading')
        .addClass('imageLoaded')
        .find('img')
        .attr('src', imageUrl)
        .show();
    $previewDiv
        .parents('table:first')
        .find('input:hidden.currentUploadedFilename')
        .val(imageFilename)
        .addClass('imageLoaded');
    $previewDiv
        .parents('table:first')
        .find('button.removeImage')
        .show();

    //New
    if(!yourCustomPreview.find('#' + imageId +'_prev').length > 0)
    {
      yourCustomPreview.append('<img id="' + imageId + '_prev" src="' + imageUrl + '"/>');
    }
    else
    {
      $('#' + imageId +'_prev').attr('src', imageUrl);
    }
}

TO REMOVE

swap out the removeImage function with this updated version:

function removeImage($removeImageButton, errorDisplayed) {

    var thumbIdToDelete = $removeImageButton.parents('table').find('[name=imageToUpload]').attr('id');
    var $parent = $removeImageButton.parents('table:first').parent();

    $.post($.uploaderPreviewer.removeImageAjaxUrl, {
        currentUploadedFilename: $parent.find('input:hidden.currentUploadedFilename').val()
    });

    $parent.find('input:hidden.currentUploadedFilename').removeClass('imageLoaded');
    $parent.find('div.previewImage')
        .removeClass('loading imageLoaded')
        .find('img')
        .hide();

    $parent.removeErrorMessage();

    if ( ! errorDisplayed) {
        $parent.find('input:file').val('');
        $removeImageButton.hide();
    }

    $('#' + thumbIdToDelete +'_prev').remove();
};

Answer №2

Could caching be the culprit?

`yourCustomPreview.append('<img src="' + imageUrl+'?'+new Date().getTime() + '"/>');`

Feel free to test out this snippet!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to sort nested JSON data in ngTable

I have successfully built an angularjs application using ngTable, however, I am facing an issue with sorting. The JSON structure is nested but the values are appearing correctly in the table. If anyone has a solution to this problem, please let me know. ...

JavaScript array as a reliable data storage solution

This is my unique jsp code where I am attempting to push certain data into a JavaScript array. <% int proListSize = proList.size(); ProfileDAO proDAO = null; for(int i = 0, j=1; i < proListSize; i++){ proDAO = ( ...

Changing a callback function into a promise in Node.js for OpenTok integration

MY FUNCTIONAL CODE (SUCCESSFULLY WORKING!) I have developed a function with callback to generate tokens and create sessions for OpenTok. This function is then exported to the application. The function //Dependencies var opentok = require('./ot&ap ...

Initiating the form with a query mark

Recently, I found myself in a disagreement with a colleague over the validity of a certain URL: <form action="?foo=bar" method="get"> According to him, using this URL can lead to troubles as the browser may struggle to correctly redirect to the int ...

My locale NUXT JavaScript files are being blocked by Content Security Policy

I've been working on implementing CSP headers for my website to ensure data is loaded from trusted sources. However, I'm facing an issue where CSP is blocking my local JS files. Here's a snippet from my nuxt.config.js: const self = 'lo ...

In my submit function, I am utilizing one Ajax call to retrieve data. I am interested in merging the data from this Ajax call with the data from a second Ajax call before submitting

Starting with an initial AJAX post to upload a file, now the goal is to have the same AJAX function grab data from another AJAX call and post it together - essentially posting the ID back to the database. Everything is functioning correctly, but the challe ...

Issues with Sound Not Playing When Button is Clicked in Python Flask

My goal is to trigger an audio sound when the Delete button is clicked. I've created an external JavaScript file and successfully linked it with Flask. index.html <a href="/delete/{{todoitem.item_id}}" class="btn btn-danger" onclick="playDelSound ...

Alignment of Inline SVG in HTML

I am struggling to align an inline SVG within a bounding DIV correctly, as shown in this example. <!DOCTYPE html> <html> <body> <div style="border: 1px solid black; height: 50px; width: 100px; vertical-align:top;"> < ...

The Geoserver encountered an error while parsing the WFS URL due to a SyntaxError: a semicolon

I'm facing an issue while trying to retrieve a JSON object from Geoserver 2.3.0 by parsing the URL and overlaying it on an OpenLayers map. Unfortunately, I am unable to get the object and keep encountering the following error: SyntaxError: missing ; b ...

Insert fresh user information into the div

Learning JavaScript is a challenge I'm tackling. I have a question that may seem trivial, but any assistance would be greatly appreciated. I currently have this code: Javascript <script type="text/javascript"> function fn(){ var Name = ...

Add some text onto the Box Component in Material UI

I am looking to replicate the hover functionality (UI) seen in this example: Desired UI Source: Since adjusting background image styles can be complex, I have opted to use the Box Component from Material UI. Within the Box Component, I have implemented th ...

Ensuring Proper Tabulator Width Adjustment Across All Browser Zoom Levels

<div id="wormGearTabulatorTable" style="max-height: 100%; max-width: 100%; position: relative;" class="tabulator" role="grid" tabulator-layout="fitDataTable"><div class="tabulator-header" role="rowgroup"><div class="tabulator-header-co ...

How can I retrieve an array of data from Firebase Firestore using React Native?

I have been working on fetching Array data from Firebase Firestore. The data is being fetched successfully, but it is all displaying together. Is there a way to fetch each piece of data one by one? Please refer to the image for a better understanding of ...

ESLint's no-unused-vars rule is triggered when Typescript object destructuring is employed

I'm encountering an issue with my Typescript code where I am destructuring an object to extract a partial object, but it's failing the linter check. Here is the problematic code snippet: async someFunction(username: string): Promise<UserDTO> ...

Making a synchronous call to a web API using JQuery

Understanding JQuery promises and deferred objects has been a bit of a challenge for me, so please bear with me. I should also mention that my application is built using React, Typescript, and ES6. Let's imagine we have an array of objects: [{ Objec ...

Utilizing JavaScript to dynamically adjust the height of one div to match the height of another div

Struggling to adjust the height of one div to match another using the following code: var aboutheight=document.getElementById('about').offsetHeight; document.getElementById('sampledogs').setAttribute("style","height:aboutheight"); Des ...

Looking to link a click event to a particular hyperlink?

I have a question about attaching click events to hyperlinks. Here is an example code snippet: $(".notice").click(function() { alert("Hello world!"); }); Below is the HTML for my hyperlink: <a href="http://www.bba-reman.com/catalogue/DetailedProdu ...

Firebug displays the class name and location twice in the right panel

When examining a div labeled with .mlm-clearfix, I noticed that Firebug was displaying this class name and its URL twice in the right panel. The style declarations given for the Easy Clear Method in relation to this class are as follows: .mlm-clearfix:bef ...

After the component has been initialized for the second time, the elementId is found to be null

When working with a component that involves drawing a canvas chart, I encountered an issue. Upon initializing the component for the first time, everything works fine. However, if I navigate away from the component and return to it later, document.getElemen ...

Transferring information to a controller using ajax in ASP.NET Core

I am encountering an issue with sending data to the controller through ajax. The value goes as "null". Can someone please assist me with this? Here are my HTML codes: <div class="modal fade" id="sagTikMenuKategoriGuncelleModal" data ...