Display a toasted notification following a refresh

After reloading the page, I want to display a toast notification confirming that the file has been uploaded. Here is my current code:

_fileUploads.delete = function(reload_on_return) {
  var filtered = root.fileUploads().filter(_ => _._id() == _fileUploads._id());
  var index = root.fileUploads.indexOf(filtered = filtered[0]);
  filtered = ko.toJS(filtered);

  swal({
    text: 'Are you sure you want to delete this file?',
    buttons: true,
    dangerMode: true,
    icon: 'warning'
  }).then(function (allowDelete) {
    if (allowDelete) {
      $.ajax({
        type: 'DELETE',
        url: '/api/gridfs/files/' + filtered._id,
        statusCode: {
          204: function(response) {
            toastrTrigger('The File has been Deleted')
            if (reload_on_return) {
              setTimeout( function() {
                location.reload();
              }, 0001);    
            }
          }
        },
        error: function (xhr, status, error) {
          console.log(xhr);
        }
      });
    }
  });
}

The page only refreshes and does not display the notification as intended.

Below is the code for the toastrtrigger function:

function toastrTrigger(message, title, type) {
  setTimeout(function() {
    toastr.options = {
      closeButton: true,
      progressBar: true,
      showMethod: 'slideDown',
      timeOut: 4000
    };
    toastr[type || "success"](message, title || 'File Uploads Repository');
  }, 500);
}

Answer №1

Scripts will not persist once the page reloads; once the document is closed, all associated scripts will disappear as well. There's no way around this limitation. The only option is to pass information to the new page solely through the URL.

One method is to include a query string in the URL of the reloaded page:

if (reload_on_return) {
  window.location.href = window.location.pathname + '?deleteSuccess=1';
}

Then, on the newly loaded page, check if a query string is present during page load:

const { search } = window.location;
const deleteSuccess = (new URLSearchParams(search)).get('deleteSuccess');
if (deleteSuccess === '1') {
  // The page was just reloaded, display the notification:
  toastrTrigger('The file has been deleted');
}

Alternatively, you can store the data in sessionStorage and retrieve it upon page load to determine if a notification should be shown.

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

Working with ng-model on an array with multiple dimensions

Currently, I am working on storing data in AngularJS. My table consists of various sections, rows, and columns. In each field, there is a dropdown list with the options "O", "T" or "E". My goal is to store these values in an array format: [section][row][c ...

Backing up a mongodb collection can be easily achieved with the help of express.js and Node.js

I am looking to create a monthly backup of my userdatas collection. The backup process involves: I intend to transfer the data from the userdatas collection to a designated backupuserdatas collection. A batch program should be scheduled to run automatica ...

Retrieve information from the object

var dataObject = {}; $('.nav ul li a').click( function() { var url = $(this).attr('href'); var key = $(this).text(); $('.content').load(url +' div', function() { dataObject[key] = $(this).html( ...

Customizing the background color of rows in Node.js XLSX using the npm package

I am currently working on a project that involves reading an Excel sheet and then coloring specific rows based on backend data. While I have successfully been able to read the sheet and create a new one with updated information, I am facing issues when try ...

The functionality of AbortController seems to be malfunctioning when used in conjunction with ajax and

I am having trouble canceling the API when leaving a page, despite using an AbortController. Here is my code snippet: import { fetchSingleList } from '@/api/scada' data() { return { abortController: new AbortController() } } beforeDestroy ...

While Ajax POST is functional on desktop, it does not seem to work on Phonegap applications or Android

I am facing an issue with a global function that does not seem to work properly in the PhoneGap Desktop app or Chrome Mobile on Android. Surprisingly, it works perfectly fine only in the Chrome PC version. The function is called using an onClick event, a ...

My controller is not recognizing the DELETE $.ajax call - what could be causing this issue?

I've encountered an issue while attempting to delete an entity using AJAX. I have the following controller method: [HttpDelete] public ActionResult Delete(int id) { //Deletion logic return Content("OK"); } Within the view, my AJAX call looks ...

Building a dynamic form in React: Fetching select data from an API, posting to another API, and automatically clearing fields upon submission

I am currently working on a form that utilizes a GET request to retrieve data from an API endpoint and then proceeds to make a POST request to another endpoint. Although I have been successful in achieving this function, I am facing challenges with reset ...

Struggling to set up a Node three.js website on a server, looking for guidance on the process

I am encountering an issue with uploading my files to the public_html folder on the server. The application consists of an HTML file, a three.js JavaScript file, and other supporting files. To run the application, I need to type "npm i" and then "npm run d ...

Populate a form with database information to pre-fill the fields

So I have this web form built with HTML, and there are certain values within the form that can be changed by the user. To ensure these changes are saved, I'm storing them in a database. My goal is to have the form automatically filled with the data fr ...

How can Symfony, Jquery, and Ajax work together to append elements to themselves?

I've implemented a jQuery function that dynamically adds rows of data from one table to another table for submission. Essentially, when a user selects an item or items (a row) in the initial table, it gets duplicated in a separate area where they can ...

When I click on my div, the color does not change as expected

Recently, I wrote a code snippet where there are 9 different div elements each assigned a ".spaces" class. The intention was to change the color of these divs upon clicking on them. However, I encountered an issue where only the first div changes its color ...

Guide to create a sliding menu transition from the viewport to the header

I am just starting to learn jQuery and I want to create a menu similar to the one on this website Specifically, I would like the menu to slide down from the viewport to the header, as shown in the template in the link. I have searched through the jQuery ...

Challenges encountered when creating routes in Reactjs

I'm currently working on a project and facing some challenges with managing routes. My frontend is split into two sections: one for the client side and the other for the admin panel, which is responsible for managing the client side. For example, if I ...

Ensure the validation of numerous input fields within a single form with the use of Vue 3 composition API

Within my application, I have implemented custom validation and validators to ensure the accuracy of various form fields. The submit button functionality is designed to remain disabled until all input fields are filled. The creation of validators involves ...

Challenge in WordPress Development

As a beginner in website building, I am looking to customize the background of my pages with a solid color. The current SKT Full Width theme I am using has an opaque background which is causing the text on my slider to blend in and not look appealing. All ...

Backend server encountered an issue with processing punycode

[ALERT] 18:13:52 Server Restarting Prompt: C:\Code\MERN_Projects\podify_app\server\src\db\index.ts has been altered (node:22692) [DEP0040] DeprecationWarning: The punycode module is outdated. Consider utilizing a modern a ...

Exploring the concept of prevState in React components

The object in my class is called "man." man: { name: "John", wife: [{"children": 2}, {"children": 3}] } this.setState(prevState => ({man: prevState.wife[0].children + 1})); I am trying to increase or decrease the quantity of the first wife's chi ...

Utilizing Ajax to dynamically submit a PHP page

I need help with implementing a single page PHP method <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </s ...

Accepting POST requests from an external source in AngularJS

I am currently working on an application that utilizes AngularJS 1.4.0 and requires the ability to receive POST data from an external source. In AngularJS, routes often use parameters in the URL format like this: .when('/section/:param', { t ...