AngularJS implemented to trigger a popup alert after a certain duration of time has elapsed since the

Can we create a popup alert that says "Error Contacting Server" when the http request does not receive any response?

.controller('items_ctrl',['$scope','$http',function($scope,$http){
    $scope.shop_id=localStorage.getItem("shop_id");
        $http.get('http://localhost/myapp/spree/stocks.php').success(function(data){
            console.log(JSON.stringify(data));
            $scope.item=data;

           });
    }])

Answer №1

It's recommended to utilize the then function instead of using the success/error methods

Below is the revised version of your code snippet:

.controller('items_ctrl',['$scope','$http',function($scope,$http){
    $scope.shop_id=localStorage.getItem("shop_id");
        $http.get('http://localhost/myapp/spree/stocks.php').then(function(data){
               console.log(JSON.stringify(data));
               $scope.item=data;

           }, function(error){
               alert("Error contacting server");
           });
        }])

Answer №2

It is important to define an error callback function when making a request.

$http.get('/someOtherUrl', config).then(handleSuccess, handleFailure);

To learn more, visit https://docs.angularjs.org/api/ng/service/$http

Answer №3

Implement a promise and set a timeout in your JavaScript code.

var cancelRequest = $q.defer();
$http.get('/someUrl', {timeout: cancelRequest.promise}).success(successCallback);
$timeout(showErrorPopup, 3000);

Once the timeout is reached, resolve the promise and then display the popup.

function showErrorPopup(){
   cancelRequest.resolve(); 
//popup code
} 

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

Is there a way to remove CSS based on the generated HTML code?

Currently tackling a project in Next.js involving custom SCSS, Bootstrap SCSS, and React-Bootstrap. Struggling with the bloated size of our main.scss file due to unused CSS. After observing that 95% of the CSS is not utilized, I aim to eliminate all unnec ...

Show a random number within a Bootstrap tooltip

I am trying to make a bootstrap popover display a random number every time it is clicked, but my current implementation is only showing the initial number generated and does not update on subsequent clicks. Below is my code snippet: <button type=&qu ...

Bootstrap modal not displaying in full view

I recently ran into some issues while using a jQuery plugin with my bootstrap modal on my website. After implementing jQuery.noConflict(), I encountered a problem where the program no longer recognized $, forcing me to replace all instances of it with jQue ...

Angular code causing an unexpected blank page to be printed again

Trying to display the content of my HTML page is proving to be a challenge. I've been utilizing angularPrint, but an issue persists in the form of a second blank page appearing in the preview alongside the actual content. Eliminating this unwanted sec ...

Most efficient method to upload numerous images without any lag

I have a website where images are loaded only when they are slightly below the viewport. This method allows the site to load initially without images and then determine which ones need to be loaded based on the user's viewpoint. When a user scrolls ...

I am encountering an issue with express-session where it is failing to assign an ID to

Seeking assistance with utilizing express-session to manage user sessions on arcade.ly. I have not specified a value for genid, opting to stick with the default ID generation. However, an ID is not being generated for my session. An example of the issue c ...

Unable to display nested JSON data from API in Vue.js

Having trouble accessing nested properties from API JSON data. The Vue component I'm working on: var profileComponent = { data : function() { return { isError : false, loading : true, users : null, ...

By default, the HTML table will highlight the specific column based on the current month using either AngularJS or JavaScript upon loading

I am working with a table of 10 products and their monthly sales data. Using Angular JS, I am looking to highlight the entire column based on the current month and year. Additionally, we will also be incorporating future expected sales data into the table. ...

What causes the scrollbar to not extend to the bottom when connected to another scrollbar via a JavaScript equation?

I have been working on a code that involves multiple scrollbars that are all linked together. When you move one scrollbar, the other two will move proportionally. However, due to differences in width, the scroller doesn't always reach the end of the s ...

Trouble with file binding function in WebApi controller

When attempting to upload files from Angular to .NET Core WebAPI, I encountered an issue with my code: [HttpPost("UploadImage")] public IActionResult UploadImage([FromForm]ICollection<IFormFile> formFiles) { var picture ...

Javascript error: Function not defined

For some reason, I seem to be hitting a roadblock with this basic function. It's telling me there's a reference error because apparently "isEven" is undefined: var isEven = function(number) { if (number % 2 == 0) { return true; ...

Passing data between Angular v1 components

I'm facing an issue in Angular v1.6.1 where I am encountering difficulties transferring data from one component to another. The navbar component, located in app\common\navbar, has a controller that pulls data from a service. The following f ...

Display the same DIV element across various HTML tabs

When two different tabs are clicked, I need to display a set of 10 Search Fields. Both tabs have the same fields, so instead of using separate DIVs, I want to use the same DIV and only change the AJAX REST End-Point based on the selected TAB. Can someone ...

Can several identical directives access and manipulate the same scope variable?

Is the scope of a controller shared when using the directive multiple times on one page? I'm not sure, but I would appreciate some help understanding this. If I define the variable 'isWidgetEnabled' in fooController, will it be shared betwe ...

Checking the status of a checkbox after submitting using AngularJs

For my first application, I am utilizing AngularJs and JavaScript to display information from an API as checkboxes. Currently, the functionality is working well, but I am unsure how to validate if any checkbox options are checked with a submit button. Aft ...

API request limit has been exceeded

This is my first time working with an API data feed that has a request limit of 1000 per hour. Surprisingly, I exceeded this limit while testing the site, which was unexpected. I'm wondering if the way the requests are being made could be the reason ...

Is it possible for me to display dynamic content and utilize a template engine like (ejs)?

Currently, I am in the process of developing a weather application to enhance my skills with express and ejs. At the moment, I'm utilizing app.get to fetch data from darkSky's API successfully, and I can display it on my index.ejs page. My next ...

Real-time port communication using PHP and C++

I am working on developing a PHP application that communicates with the COM port on a local machine. The challenge I am facing is that reading from the COM port in PHP is not straightforward due to a timeout reading bug. To overcome this issue, I have imp ...

Add an error message to my throw object within the JSON response

I need to include the error message from the JSON Response of the API in my error object {'status': response.status, 'msg': ''} if there is one, or else just throw the error object without a message. However, currently the thr ...

Exploring the life cycle of React.js components, how state behaves within them, and the asynchronous nature

There seems to be an issue with the expected data result and the actual data result. Even though the fetchData() and fetchnumberOfCommits() methods are being called from the componentWillMount(), the array is empty at first. However, the render method is b ...