Reverting Back to Original Background Image in JQuery

In my web application, users have the ability to create and view interactive stories...

One of the features allows them to change the background image by uploading a new image file. The file path of the uploaded image is stored within a javascript object and then posted as JSON to a MongoDB database.

When I replace the uploaded image with a new one and save it using the app, everything works perfectly.

However, when I retrieve the JSON data from the database and try to use the stored URL later on, it reverts back to the old image instead of displaying the updated one...

This snippet of code is responsible for saving the story...

function saveStory(){

var numPages = $('.page').length;

var book = {};

$.getJSON('../scripts/getUser.php').done(function(data){
    book.title = title;
    book.user = data._id.$id;
    book.pages = [];

    var page;
    var link;

    for (var i = 0; i < numPages; i++){
        var numLinks = $('#p' + i + ' .link').length;
        page = {};
        page.text = $('#p'+i+' .textarea').text();
        page.image = $('#p'+i).css('background-image').replace(/^url\(["']?/, '').replace(/["']?\)$/, '');

        page.links = [];

        for (var j = 0; j < numLinks; j++){
            link = {};
            link.text = $('#p'+i+'l'+j+' .linktext').text();
            link.locale = $('#p'+i+'l'+j+' .locale').text();

            page.links.push(link);
        }
        book.pages.push(page);
    }
}).then(function(){ $.post('../scripts/addstory.php', {book: book})});
 }

This piece of code handles opening the story...

function openStory(){
var story = $('#thestory').text();
$.post('../scripts/getstory.php', {story: story}, function(book){

var numPages = book.pages.length;

    for (var i = 0; i < numPages; i++){

        var numLinks = book.pages[i].links.length;

        $('#content').append("<div id='p"+ i +"' class='page'><div class='textarea' contentEditable='true'>" + book.pages[i].text + "</div></div>");

        $('#p'+i).css('background-image', 'url(' + book.pages[i].image.replace(/^url\(["']?/, '').replace(/["']?\)$/, '') + ')');

        for (var j = 0; j < numLinks; j++){
            $('#p' + i).append("<div id='p"+ i +"l"+ j +"' class='link'><div class='linktext' contentEditable='true'>"+ book.pages[i].links[j].text +"</div><div class='locale' contentEditable='true'>"+ book.pages[i].links[j].locale +"</div></div>");
        }
    }
}, 'json');
 }

I confirmed that the correct URL was being saved in the JSON data.

After saving the story and refreshing the page, the openStory() function is called and the image URL reverts back to the old one!

The confusing part is that the URL value in the database has been updated, yet it somehow retrieves the old value.

Does anyone have a solution for this issue?

Answer №1

It appears that the provided information may not be sufficient to address this issue. It is likely that the error lies within the html or possibly php code.

Can you please provide the value stored in #thestory?

Additionally, what is the value of the 'image' parameter returned by getstory? If it is accurate according to the server response, the issue may be originating from the php code rather than JavaScript.

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

Using CSS selectors in Framework7 Vue allows for precise targeting and styling

I am currently working on developing a Cordova/Phonegap application using vue.js and the Framework7. I have been able to utilize functions like "onClick" by using the "v-on:click="OnClick" attribute within an HTML element. It's worth noting that Frame ...

There seems to be an issue with parsing JSON using Jongo

Utilizing a mix of Java Play Framework, MongoDB, and Jongo for a simple web CRUD app, I am encountering a JSON parse exception that seems to be triggered by a closing curly bracket at the end of the statement. Despite there being no illegal characters in m ...

Is there a specific approach for linking together two AngularJs service calls and executing a function with the obtained data?

I am trying to chain two service calls together and then filter the data using a forEach loop. However, I am encountering a TypeError: "SocialMediaUserService.channelProfiles is not a function" error in Chrome. Interestingly, this code works perfectly fin ...

Executing a fundamental three.js program

After downloading three.js from the official site, I encountered a strange error while trying to run a basic file. However, when I replaced the local import of the three.js file with a CDN, it started working properly. Can someone assist me in getting the ...

Utilizing MongoDB's Java Driver for aggregation operations with a regex filter

Currently, I am working with MongoDB Java Driver version 3.6.3 and I have a requirement to build a regex query using group by aggregation to fetch distinct values. Consider the following JSON data: [{ "name": "John Snow", "category": 1 }, { "name": ...

Troubleshooting the Alignment Issue in Angular Material Expansion Panel Header

I have implemented an Angular 14 Material Expansion Panel as shown in the code snippet below... <mat-nav-list> <a mat-list-item role="listitem" class="list-item-setting" id="emailTemplatesId" matTooltipPosition=&quo ...

Optimizing responsiveness and side margins for high-resolution displays

Struggling with creating a website design with Bootstrap. My goal is to add margins on the sides when the screen size increases, but once I achieved it, the responsiveness of the page got disrupted. To incorporate the side margins, I enclosed the entire b ...

Guide to downloading a CSV file directly from a webpage built with vue.js

Delving into the world of vue.js, I find myself pondering over how to incorporate a download link in my webpage for a CSV file stored locally. In my component Template.vue, I have the following structure: <a :href="item.loc" download> {{item.title ...

Isolated directive with two-way binding in Angular, but the property is not defined?

Confusion arises when trying to understand the concept of two-way data binding. Let's take a look at the code snippet below: .directive('mupStageButtons', function() { return { transclude: true, template: '<span ...

Showing AngularJS information on Views

After successfully implementing static HTML with views, as shown in this example: https://embed.plnkr.co/MJYSP01mz5hMZHlNo2HC/ I am now facing a challenge with integrating the angular-ui accordion within ng-view. You can view the accordion I am attemptin ...

Create JSON data from SQL Server

I'm looking to create a JSON string from a SQL table by using the FOR JSON AUTO qualifiers, where one or more columns store data in JSON format. For example: Table: Persons First_Name | Family_Name |City | Children --------------+-------- ...

Shift a div along the x-axis, followed by the y-axis movement

Provided below is an example that showcases my script: http://jsfiddle.net/jewb/tM5h7/4/ The script I have written looks like this: var minHeight = $(window).scrollTop(); var maxHeight = $(window).height(); var middleHeight = (maxHeight + minHeight) / 2; ...

Guide to reading JSON files with a personalized approach

Below is a JSON object structure that I am working with: { "db": { "name": "db", "connector": "memory" }, "MySql": { "host": "localhost", "port": 3306, "database": "users", "username": "root", "password": "", "name": "MySql", ...

Utilize JavaScript API to style cells within an embedded Excel spreadsheet

Does a JavaScript API exist for formatting cells within an embedded excel file? Currently, we are using the EWS DOM API to format cells, but it has proven to be unstable and dependent on the browser. ...

Script modifies div dimensions independently of CSS styling

Recently, I received assistance from this community in creating a script that displays random images from an array within 4 divs. Each image changes upon refresh or with a timer. HTML: <section> <div id="square_1" class='box'> ...

The MongoDB aggregation fails to return results when querying nested keys

(Update: After refining the question, it appears that the issue at hand is a bit more complex than initially thought in relation to a similar query.) Imagine having these two collections: products { _id: 'AAAA', components: [ { type: & ...

The construction was unsuccessful due to errors in the webpack process

I encountered a sudden error in my Next.js app. Is there any solution available to resolve this issue? ./pages/_app.tsx Error: [BABEL] C:\Projects\skribeNew\app-web\pages\_app.tsx: You provided us with a visitor for the node type T ...

html5 Showing and hiding div elements

Here is a snippet of code to consider: @using App.Models @model App.Models.AllPeopleViewModel @{ ViewBag.Title = "Index"; } <html> <head> </head> <body> @foreach (Customer person in Model.Content) { <div class=&qu ...

Swapping out a JavaScript canvas element for a different element

Currently, I am experimenting with a customized face-to-gif application. You can access the prototype by visiting this link: . This app utilizes your webcam to create a GIF. I am in the process of streamlining the user interface and intend for the recordi ...

What is the process for generating Points with Three JS and React-Three-Fibre?

My current stack includes React, Three JS, and React-Three-Fibre I am aiming to generate an array of 100 Points with random colors, positions, and sizes. However, I find myself struggling with the process and would like to achieve this by predefining buff ...