updating the background image in CSS after uploading a photo using Ajax

Whenever I click on an element, it triggers an input dialog that allows me to upload a photo. The server then responds with a JSON OBJECT containing 4 items: NAME, TYPE, HEIGHT, WIDTH.

My goal is to refresh the element's background with the newly uploaded photo after a successful ajax upload process. Here is what I have tried so far:

JS:

$(document).ready(function() {
    $("input[name!='photo_1']").parents('.fileinput-wrapper').find(".label").remove();

    $("input[type=file]").on('change', function(){
        $(this).parents('label').find('.fileinput-preview').css('background','url(http://localhost/project/assets/images/ajax-loader.GIF) no-repeat center center');
        var selectedElement = this;
        var name = $(this).attr('name').toString();
        $('#upload').ajaxSubmit({
            dataType:'json',
            data: {name: name},
            beforeSubmit: function(){
                $(selectedElement).parents('label').find('input[type=file]').attr('disabled','disabled');
            },
            success: function(data) {
                $(selectedElement).parents('label').find('.fileinput-preview').css('background',"url('http://localhost/project/assets/images/loading.png') no-repeat center center");
                $.each(data, function(index, item) {
                    $(selectedElement).parents('label').find('.fileinput-preview').css('background', "url('http://localhost/project/uploads/" + item.NAME + "') no-repeat center center");//**replacing part**
                });
                $(selectedElement).parents('label').find('input[type=file]').removeAttr('disabled');
                return false;
            },
            error: function(xhr) {
                alert(xhr.responseText);
                return false;
            }
        });
    });

});

It successfully replaces the background, but the image does not load and appears blank. Any suggestions on what I should do next?

Answer №1

You've overlooked a single ':

.css('background',"url('http://localhost/project/uploads/"+ item.NAME +")

It should be corrected to

.css('background',"url(http://localhost/project/uploads/"+ item.NAME +")

The url parameter doesn't require '', url(path/to/file.jpg) works perfectly. However, you're only setting one. Also, is the file extension included in item.name?

You can verify what url is being set after the success by using the dom inspector, or simply do a console log of the complete string

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

Extracting a targeted substring from a JSON object using Python

Currently, I am attempting to extract specific data from a JSON response received from Spotify. Here is my existing code: with requests.Session()as(c): url = 'https://accounts.spotify.com/en/login?continue=https:%2F%2Fwww.spotify.com%2Fint%2Facco ...

"Is there a way to transmit a JSON with just one word (without a key) to springMVC

I am facing a challenge with my API for the front end. Currently, I am using Postman to send a single number (8). I am looking to implement a similar process in Postman @RequestMapping(value="/query",method=RequestMethod.POST) @ResponseBody public String ...

Ways to properly release file descriptors in write streams

I'm currently working on a code snippet that showcases what I'm aiming to achieve: const fs = require('fs'); var stream = fs.createWriteStream('/tmp/file'); stream.once('open', function(fd) { for (var i = 0; i ...

Attempting to create an animated carousel slider

I've been working on creating a carousel animation that displays 3 images, slides them to the left, and brings in new ones. I'm feeling a bit stuck and could use some assistance. Check out my work so far on this fiddle link: http://jsfiddle.net/ ...

Uploading files asynchronously with Erlang Cowboy using AJAX

I am facing an issue with AJAX file uploading to Erlang Cowboy. I am able to stream the file upload with mutltpart/form-data. <form method="post" enctype="multipart/form-data"> However, I am unable to stream the file uploading using AJAX because it ...

Using JavaScript code to sift through and eliminate irrelevant data

Recently, I started learning about angular js and came across a link from which I need to extract a list of names and ids. I successfully retrieved the list in json format, but now I need to filter out unwanted items. The criteria for filtering is based ...

problem with creating a django template script

Hello, I am currently working on a code that is responsible for executing various functions within the template. I have utilized scripts to verify these functions using if-else statements and for loops. However, I am encountering some errors during this pr ...

Creating responsive images in Bootstrap columns

I've found a solution to my issue with large images, but I am still struggling with smaller images not fitting well into larger spaces. Essentially, I created a CMS for a user who required templates with various bootstrap columns as content areas. Cu ...

Develop an XML document with the use of either Javascript or PHP

I have an XML file that contains information about bracelets with photo details. <bracelets> <photo filename="b1.jpg" thumbnail="a1.jpg" description="aa" /> <photo filename="b2.jpg" thumbnail="a2.jpg" description="aa" /> & ...

Generating hyperlink regions dynamically

I am looking to create an image with a link map that will contain multiple areas that need to be updated frequently. Instead of constantly recreating the areas every few seconds, I want to generate them only when the user clicks on the image. I initially ...

Vanishing Span in CSS3 Flexboxes

I came across this particular HTML code: <div class="panel panel-info"> <div class="panel-heading">Person</div> <div class="panel-body"> <div class="data"> <p class="keys"> ...

Angular - Electron interface fails to reflect updated model changes

Whenever I click on a field that allows me to choose a folder from an electron dialog, the dialog opens up and I am able to select the desired folder. However, after clicking okay, even though the folder path is saved in my model, it does not immediately s ...

Breaking the line when combining an image_tag and text in a Rails navbar

Looking for some help combining a logo and brand name in my Bootstrap navbar. I'm running into an issue where there is a line break separating the logo and text. Can someone provide some assistance? <%= link_to image_tag("brand_logo.png") + " Bran ...

How can I randomly choose 5 TR items and show them to the user?

How can I randomly select and display 5 questions for the user? The rest of the questions should be hidden on the page and only 5 questions should be displayed. This is a sample code. I want the user to see 5 questions out of many questions when the page ...

On smaller screens, the top placement of right sidebar links is necessary

Our website layout is organized into 3 main sections: the top part contains the main menu, followed by the main content and a sidebar specific to each page. The main content and sidebar are structured using bootstrap col-* classes. On small screens, I en ...

What is the best way to extract the variable inside a script tag as a JSON value?

Hey, I need help figuring out how to convert a JavaScript variable into a JSON value using Python with the help of libraries like BeautifulSoup and requests. I attempted to solve this issue by following a similar topic on Stack Overflow, but unfortunately ...

jQuery not targeting absolute positioned duplicates of the <div>'s

(Please find the code link at the bottom of this question) I have been working on a radial menu for a web project. However, I've encountered an issue that has me stuck for hours now. No matter what I try, I can't seem to get any response from th ...

"Enhancing User Interaction: The Dynamic Trio of Ajax, Php, and MySql in Comment

I have successfully developed a basic commenting system, featuring a form with two fields: name and comment. Upon submitting the values, it utilizes Ajax to dynamically add the comment to the existing page without refreshing the entire content. My next ob ...

Modify the templateUrl in routeProvider according to the user's authorization

Is there a way to dynamically change the templateUrl in the router provider based on user permissions? Here's an example of what I'd like to achieve: $routeProvider .when('/',{ if(user) templateUrl:'app/views/pages/h ...

Issues arising from URL encoded characters that fail to get rewritten

I have set up rules for dynamic redirects to point old URLs to new locations. However, I encountered an issue where the redirect failed when URL Encoded Characters were present in the URLs. Here is an example of such URLs: www.example.com/ebc-drama-yebet- ...