1

I'm working on converting a jquery ajax call to an angular $http call, but for some reason am returning a 404 status. Here is the original jquery call.

function getStaffInfo(){                    
    $.ajax({
        url: 'https://my.website.com/j/wkr/stafflist.php',
        data: {f: 'staff'},
        dataType: 'jsonp',
        jsonp: 'callback',
        jsonpCallback: 'vcLoadStaff',
        success: function(){
                                //alert("success");
        }
    });
}

Here is the angular $http call:

app.service('staffList', function($http){

var staffList = {};

$http.jsonp('https://my.website.com/j/wkr/stafflist.php', {"f":"staff"})
.success(function(data, status, headers, config) {
        console.log(data);
        staffList = data;
    }).error(function(data, status, headers, config) {
        console.log(status);
});

return staffList;

});

Am I missing something in my angular code?

byrdr
  • 5,197
  • 12
  • 48
  • 78

3 Answers3

1

I believe you need to append ?callback=JSON_CALLBACK to your URL.

$http.jsonp('https://my.website.com/j/wkr/stafflist.php?callback=JSON_CALLBACK', {"f":"staff"})
.success(function(data, status, headers, config) {
        console.log(data);
        staffList = data;
    }).error(function(data, status, headers, config) {
        console.log(status);
});

Edit: Just to clarify, when you make that change, the resulting data will be wrapped in JSON_CALLBACK([...]). Also check out this relevant answer.

Community
  • 1
  • 1
Noel
  • 3,288
  • 1
  • 23
  • 42
1

The http service returns the payload as a promise so you may find you have to call success on the service inside the controller you are using it in like so..

app.service('staffList', function ($http) {
    return {
        getList: function () {
            $http.jsonp('https://my.website.com/j/wkr/stafflist.php?callback=JSON_CALLBACK', {"f":"staff"})
        }
    };
});

app.controller('staffController', [$scope, staffList, 
    function($scope, staffList) {

        staffList.getList().success(function(data, status, headers, config) {
            console.log(data);
        }).error(function(data, status, headers, config) {
            console.log(status);
        });
    }
]);

The angular $q service may also be useful although I found the above implementation some what easier to use.

https://docs.angularjs.org/api/ng/service/$q

0

At angular documentation your $http.jsonp can be like this:

jsonp(url, [config]);

So you may try

$http.jsonp('https://my.website.com/j/wkr/stafflist.php', {data:{"f":"staff"}})

https://docs.angularjs.org/api/ng/service/$http#jsonp

Seth
  • 528
  • 3
  • 16
  • 32
selami
  • 1
  • 3