What is the best method for sending an angularjs $http POST request when a user refreshes a page?

controller:

app.run(function ($rootScope, $templateCache) {
    $rootScope.$on('$viewContentLoaded', function ($scope, $http) {     
        $templateCache.removeAll();
        alert("refreshing.....");
        $http({
            url: '/angularjs-restful/check/check-session',
            method: "POST",
            data: {},
            isArray: false
        }).success(function(data, status, headers, config){
            alert("AJAX call successful.....");
            console.log('status code: ' + status);
            console.log('returned data: ' + data);
        }).error(function(data, status, headers, config){
            alert('An error occurred');
        });        
        alert("end of function.....");
    });       
});

Is there a way to make an AJAX call when the user refreshes the page either by pressing F5 or manually refreshing with a mouse click? The URL points to a REST service that returns either true or false.

Answer №1

One way to detect when the user refreshes a page is by using the window.onbeforeunload function, which triggers the unload event upon pressing F5.

function ctrl($scope, $window) {
    angular.element($window).bind('beforeunload', function() {
        console.log('Perform AJAX call');
    });
}

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

Bootstrap and Rails 6 without webpack: default Bootstrap JavaScript functionality malfunctioning

I recently developed a new rails app using the --skip-webpack-install option, and while the default bootstrap styles are functioning properly, some of the JavaScript components don't seem to be working as expected. Even though my application.js file ...

The logic is not quite coming together in these arguments

//Resolved In my attempt to add the parameters together and then divide by 2 to pass the result into the sqrt method, I encountered an issue where only the last parameter of the function was being returned. When using typeof, it indicated that the argume ...

"Effortlessly Engage Users with Rails and AJAX Comment Posting

Running a simple blog app dedicated to video game reviews, I encountered an issue with AJAX. As a self-taught student developer, I'm facing a challenge where posting comments on review pages triggers a full page refresh instead of dynamically updating ...

Error encountered with Jquery script: "Unauthorized access"

I'm currently working on a script that involves opening a child window, disabling the parent window, and then re-enabling the parent once the child window is closed. Here's the code snippet: function OpenChild() { lockOpportunity(); if (Clinical ...

Creating a Vue 3 component and embedding it as an HTML string

Currently, I am tackling a project in vue.js (version 3) and find myself in a situation where I need to incorporate the HTML output of one component into another component's method. In my Vue project, I have developed an SVG component as shown below: ...

Tone.js is failing to sync sequences during playback

I'm currently working on developing a sequencer using Tone.js. Right now, I have a basic sequence that plays when the user clicks the play button. However, I've encountered an issue where if the button is pressed to pause and then played again, t ...

Puppeteer is experiencing a hanging issue on Raspberry Pi Zero due to a timeout being exceeded

I am encountering difficulties with running puppeteer on my Raspberry Pi Zero, following the steps outlined in this tutorial. Here is what I have attempted so far: $ sudo apt-get install chromium-browser chromium-codecs-ffmpeg --yes $ npm init -Y $ npm ...

Mobile devices do not support internal link scrolling in Material UI

Currently, I'm utilizing internal links like /lessons/lesson-slug#heading-slug for smooth scrolling within a page. While everything functions perfectly on desktop, it ceases to work on mobile view due to an overlaid drawer nav component. Take a look a ...

Rubaxa-Sortable encountered an error while attempting to execute the 'matches' function on the 'Element': the selector '>*' is invalid

I have implemented Rubaxa Sortable JavaScript library in my Vue.js project. It works perfectly fine with <ul><li> elements, but when I try to use it with table rows, I encounter this error during drag-and-drop: Sortable.min.js:3 Uncaught DOMEx ...

Unable to locate 'this' in the callback function triggered by tinymce

I am experiencing an issue with my Angular2 app that uses tinyMce as an HTML editor. The problem arises when I need to convert the URLs in the HTML content using my REST API. I tried using the "urlconverter_callback" function from tinyMce, but I encountere ...

Utilizing sourcemaps in ionic for seamless linking

I've encountered an issue with source maps or a similar feature. After inserting console.log(...) in my code, the message appears in the console but links to the compiled JavaScript file instead of the original TypeScript file. Have I overlooked som ...

retrieve a value from an eventListener embedded within a forof iteration

How do I pass the coin object returned from the displayCurrencies function to the getCoinId function as a parameter for making an API call to retrieve specific coin data? This is the function created to return the value: let returnID = (value) => { r ...

Encountering a display issue within a port using Express

Recently, I enrolled in an advanced ExpressJS course. While exploring the course website, I stumbled upon the "hello world" section. Intrigued, I decided to copy and paste the code provided below: const express = require('express') const app = ex ...

Tips for ensuring that your website can recall which call-to-action (CTA) has been selected for redirection

I'm attempting to create a bilingual webpage in Spanish and English. My goal is to have a main page where the user selects the language, and once chosen, the page remembers the language preference for future visits instead of prompting the choice agai ...

What is the best way to remove "autocomplete= off" from JavaScript?

Struggling with using selenium to remove the autocomplete = off attribute. This code snippet is causing me some trouble. input type=text id=searchInput autocomplete = off placeholder="输入城市名称、拼音查询天气"><span cla ...

The table will remain empty for eternity as the page is being loaded using ngRoute

Currently, I am utilising Angular routers. app.config(function($routeProvider) { $routeProvider .when('/comment/list', { templateUrl: 'commentList.htm', controller: 'mainController' }) }); ...

Encountering unexpected props in Components upon clicking links within React-router

I am currently developing a User page that displays individual profiles for each user. The profile page is functioning properly upon initial loading. However, I am facing an issue where if I am viewing the profile of user1 and then navigate to the profile ...

Creating unique sizes for each quad in Three.js using InstancedBufferGeometry and ShaderMaterial

I'm working on creating a visually dynamic scene filled with points of varying widths and heights. The challenge I'm facing is figuring out how to manipulate the vertices in the vertex shader to achieve customized sizes for each point. Here' ...

Regex pattern to replace the zero preceding two times within a string based on distinct criteria

I need to transform the string XY4PQ43 using regex in JavaScript. The output should be XY04PQ0043. Specifically, I want to add a zero prefix to the first number if it is a single digit to ensure it has 2 digits, and for the second number in the string, I w ...

Utilize React Redux to send state as properties to a component

When my React Redux application's main page is loaded, I aim to retrieve data from an API and present it to the user. The data is fetched through an action which updates the state. However, I am unable to see the state as a prop of the component. It s ...