KingKongFrog
KingKongFrog

Reputation: 14429

How do I repeat an ajax call in angular.js and stop it based on response value

I have a simple controller that runs an ajax call. What is the most optimal running this ajax call every 15 seconds instead of just once. And how do I also stop the call?

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)
    })
})

Upvotes: 0

Views: 1405

Answers (3)

binariedMe
binariedMe

Reputation: 4329

function httpCall (){
        $http({
            method: 'GET',
            url: '../ajax/my_script.php', 
        })
         .success(function(data, status, headers, config) {
            if(data == "expectedData") //condition to stop recursive ajax.
              $tiemout(httpCall, 15000);
        })
}

Upvotes: 4

Ajay Narain Mathur
Ajay Narain Mathur

Reputation: 5466

You can use $interval service and stop it at an event as cancel(promise)

eg:

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

clear interval as:

$interval.cancel(promo)

Upvotes: 3

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

You could do it just by using $interval

var ajaxCall = function(){
    $http({
        method: 'GET',
        url: '../ajax/my_script.php', 
    })
    .success(function(data, status, headers, config) {
        //on some condition
        if(data.length == 0) //just for demonstration..you could add your own condition.
            $interval.cancel(interval); //this is to cancel interval
        console.log(data)
    })
}

var interval = $interval(ajaxCall,15000)

Upvotes: 1

Related Questions