What is the best way to continuously make an ajax request in Angular.js and terminate it depending on the response received?

I am looking for advice on how to optimize my controller in order to run a periodic ajax call every 15 seconds instead of just once. Additionally, I am wondering how I can stop the call when needed.

myApp.controller('myCntrl', function($window,$scope,$http,$routeParams,$location) {

    $http({
        method: 'GET',
        url: '../ajax/my_script.php', 
    })
    .success(function(data, status, headers, config) {
        console.log(data)
    })
})

Answer №1

function makeHttpCall (){
        $http({
            method: 'GET',
            url: '../ajax/my_script.php', 
        })
         .success(function(response, status, headers, config) {
            if(response == "expectedData") //checking for expected data to prevent recursive ajax calls.
              $timeout(makeHttpCall, 15000);
        })
}

Answer №2

To stop a running timer in AngularJS, you can utilize the $interval service and terminate it on a specific event using cancel(promise)

For example:

var promotionTimer = $interval(function(){
$http({
        method: 'GET',
        url: '../ajax/my_script.php', 
    })
    .success(function(data, status, headers, config) {
        console.log(data)
    })
}, 1500);

To clear the interval, use:

$interval.cancel(promotionTimer)

Answer №3

One way to achieve this is by utilizing the $interval method.

var fetchData = function(){
    $http({
        method: 'GET',
        url: '../ajax/my_script.php', 
    })
    .success(function(data, status, headers, config) {
        // Add your conditional statements here
        if(data.length == 0) // Example condition - customize as needed
            $interval.cancel(interval); // Cancel the interval
        console.log(data)
    })
}

var interval = $interval(fetchData, 15000)

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

JavaScript variable not refreshing its value after submitting an HTML form

In my HTML form, I have 8 textboxes enclosed in div tags with IDs ranging from fa1 to fa8. By default, two of the textboxes are visible while the remaining six are hidden. To toggle the visibility of these divs, I've implemented two buttons - addfa an ...

Fetching data from a database for Vue.js using the Summernote editor

I previously inquired about integrating summernote with vue.js and received a helpful response here. It worked seamlessly with v-model binding. However, I encountered an issue when attempting to load data from the database for an edit page. The data was n ...

Is it possible to import a class from a different project or module in TypeScript?

I am attempting to modify the build task in Typescript within this specific project: https://github.com/Microsoft/app-store-vsts-extension/blob/master/Tasks/app-store-promote/app-store-promote.ts I am looking to incorporate an import similar to the one be ...

You are unable to reference a member within the embed in discord.js v13

I created a system for logging join and leave events in my server. However, I encountered an issue where the member is not mentioned when the bot sends the embed in the channel. Here is a snippet of my code: client.on('guildMemberAdd', guildMemb ...

Transform your data visualization with Highcharts enhanced with the stylish appearance of DHTML

I am currently using a dhtmlx menu with my charts, specifically the legendItemClick event. It worked perfectly when I was using highcharts 3.0.1. However, after upgrading to version 4.1.7, the function legendMenu_<?=$id?>.showContextMenu(x,y) in the ...

Each loop in the forEach function triggers the mouseup event

I am currently utilizing a foreach loop: objects.forEach(function(object) { var button = '<tr><td>' + object.object.code + '</td><td>' + formatDistance(1456000) + &apos ...

Differences in HTML animations can be seen when comparing Google Chrome to Microsoft Edge. Looking for a workaround for autoplay to ensure

My intro video animation is facing recording difficulties due to the autoplay policy in Google Chrome. It seems nearly impossible to capture it accurately. If only autoplay could function for an offline HTML file, my issue would be resolved. Unfortunately ...

Determining in Express.js whether headers have been sent or not

As I develop a library that involves setting headers, I aim to provide a personalized error message in case the headers have already been sent. Rather than simply letting it fail with the default "Can't set headers after they are sent" message from No ...

"If the radio button is selected, ensure that the element has the required attribute added

In my form, I have radio buttons and an input field. When any of the three top radio buttons are checked, I need to make the input field required. Here is my code: <ng-form name="addShareholderForm"> <form name="form.addForm" class="form-validati ...

What are the best methods for authenticating and authorizing Angular get and post requests within AspNetCore 2.2?

After setting up a dotnet angular project, I proceeded to implement authentication in the StartUp.cs file with the following code: public void ConfigureServices(IServiceCollection services) { services.AddScoped<IPasswordHasher<CustomUser>, ...

Retrieve the overall number of Formik errors for a specific field array

In the given Yup validation setup below, there is a nested Formik FieldArray: parentLevel: Yup.array().of( Yup.object({ childrenLevel: Yup.array().of( Yup.object({ childName: Yup.string().required('Name is required') ...

React Hamburger Menu not working as intended

I am facing an issue with my responsive hamburger menu. It is not functioning correctly when clicked on. The menu should display the navigation links and switch icons upon clicking, but it does neither. When I remove the line "{open && NavLink ...

In JavaScript, a "switch statement" retrieves a test value from a "input type text" by accessing the value using getElementByName.value

Attempting to test 7 possible values for the variable 'a' by passing it to a function from user input in seven 'input type text' boxes, then checking each value individually with clicks on 7 'input type image' elements. Howeve ...

Arrange array items according to the values of two attributes

Within my array of N objects, each object is structured with the following properties: { id: 'an id', description: 'a description', isUser: true/false } My goal is to sort this array based on two criteria: Firstly, any object w ...

Having trouble with window.setInterval in AngularJS?

My coding snippet involves the use of the setInterval method: function MyController($scope) { $scope.clock = new Date(); var updateClock = function() { $scope.clock = new Date(); }; setInterval(updateClock, 1000); }; The HTML asso ...

Caution: React does not support the `textColor` prop for a DOM element

Receiving an alert message saying: Warning: React does not recognize the 'textColor' prop on a DOM element (all other functionalities are functioning properly). This is how I'm using it in my component: import { ImageWithFallback, Paper, Ta ...

What is the best way to save the raw text or event-stream data from a JavaScript get request when the server is continuously loading?

Currently, I'm attempting to fetch some basic data from an API. Here is the URL for the request: The issue lies in the fact that the server appears to keep refreshing the page constantly. This endless loading occurs both when using a browser and with ...

What steps can I take to stop my browser from displaying the "waiting for MyHostName" message while performing an ajax Post/Get operation?

Whenever I access a website using Chrome, a message appears in the status bar saying "Waiting for MyHost name" along with an Ajax Loader circle in the browser tab. Here is a javascript function that I am working with: function listen_backend_client_reques ...

Guide for verifying the minimum and maximum values when selecting a particular product from a dropdown menu

My goal is to implement validation for the width textbox when a user selects a specific product from the dropdown menu. The validation should only allow the user to enter a value between 10 and 200. I have successfully retrieved the selected value, but I ...

The Electron forge project from publisher-github is failing to detect the environment variable GITHUB-TOKEN

I've set up my .env file with the correct token, but I encountered an error when trying to publish my package on GitHub. An unhandled rejection has occurred inside Forge: Error: Please set GITHUB_TOKEN in your environment to access these features at n ...