Cannot retrieve JSON data from Last.FM's API - javascript

I am working on a school project and have run into trouble. Namely, I am building a simple AngularJS app which shows some kind of a radio chart based on Last.FM's data.
However, when trying to access the API, I never get a response.
This is the code that I use for accessing:
APIservice.getChartTracks = function () {
return $http({
method: 'JSONP',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=MY_API_KEY&format=json'
});
}
Afterwards, when I do something like this:
APIservice.getChartTracks().success(function (response) {
$scope.tracks = response.tracks.track;
});
the success() method never gets called. If I were to change the url to this one (found it on some online tutorial), I get a response and everything.
How should I go about accessing Last.FM's API?
Thanks in advance.

With $http, the method to use is GET, not JSONP. Write:
return $http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=MY_API_KEY&format=json'
});
Or use the shortcut:
return $http.get('http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=MY_API_KEY&format=json');

Related

rest api authorize using javascript

I was trying to create a api web data connector for tableau, but stuck in the authorization phase. I have a header key and value (e.g. api_header, value123) needs to pass using javascript.
// Download the data
myConnector.getData = function(table, doneCallback) {
$.getJSON("https://testapi/data",
function(resp) {
var tableData = [];
How to pass the key and value here?
I'm not sure .getJSON supports headers, at least the documentation doesn't mention them.
According to this answer, you could use .ajax instead like so:
$.ajax({
url: 'https://testapi/data',
headers: { api_header: 'value123' }
});

how do i call web service from within a web service

i am really new to the REST world, or in fact the WebApp side of java, so please don't mind if it's a silly question.
I have a web page where pressing a button will call the following JS function:
function testFunction(){
$(document).ready(function() {
$.ajax({
url: "http://localhost:8080/test/webapi/myresource",
type: 'get',
success: function (data) {
console.log(data)
}
});
});
}
where the above url is handled by my OWN web service(which is in java), that is the above GET will call the following Web Service:
#Path("myresource")
public class MyResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() {
return "Got it!";
}}
All i wanna do here is instead of returning "Got It", i wanna call another javascript function(dedicated to handle server kind of request) involving EXTERNAL rest call such as this:
function externalResource() {
$(document).ready(function() {
$.ajax({
url: "any_external_rest_call",
type: 'get',
dataType: 'json',
success: function (data) {
document.getElementById('demo').innerHTML = "Perfect"
}
});
});
}
where i wanna return the data from the externalResource function to getIt() to finally the testFuntion(), i know its possible, but couldn't find much of the details online. It would be really helpful if someone could clear this up to me.
You cannot call JavaScript code from your REST method in Java. However, you can use the ClientBuilder of the javax.ws.rs.client package.
Your method could look like this:
#Path("myresource")
public class MyResource {
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getIt() {
client = ClientBuilder.newClient();
target = client.target("http://api.anotherRestService.com/details/")
return target.request(MediaType.APPLICATION_JSON)
.get();
}
}
This is just an example, I didn't try it in a real environment, but this is how you can do it. Now, you can call with your JS method testFunction the REST method of your Java backend. In you REST method getIt you call another rest service with the created client. The result of the second rest call is returned to your JS method testFunction.
Take a look at his: RestTemplate. This is Spring, however. Seeing as you are using JAX-RS maybe take a look at this: Jersey.
The flow you describe is not possible, it is however possible to chain several requests while using data from the response of the previous response:
$(document).ready(function() {
$.ajax({
url: "http://localhost:8080/test/webapi/myresource1",
type: 'get',
success: function (data) {
$.ajax({
url: "http://localhost:8080/test/webapi/myresource2?id="+data.id,
type: 'get',
success: function (data) {
console.log(data)
}
});
}
});
});
If you wish to call another URL from your server, its a redirect call. Following would be an example server side code if you are using Spring framework.
#RequestMapping("/to-be-redirected")
public RedirectView localRedirect() {
RedirectView redirectView = new RedirectView();
redirectView.setUrl("http://www.google.com");
return redirectView;
}
As others have mentioned, you can also use Spring RestTemplate to do this.

Retrieving Json Object from action method in ASP.NET

I have searched and seen many solutions but yet I still am not getting any progress. I get no errors within the console and get nothing in return from the ajax request.
Here is action method code:
[HttpGet]
public ActionResult GetEmployees()
{
AWEmployeeModel aw = new AWEmployeeModel();
aw.ID = 0;
aw.Name = "Selena";
aw.Position = "Cashier";
aw.Department = "Finance";
return Json(aw,JsonRequestBehavior.AllowGet);
}
And here is my ajax call within my controller:
EmpApp.controller("AWEmpControl", function ($scope) {
loadEmployees();
function loadEmployees() {
$.ajax({
url: "/AWEmployee/Index/GetEmployees",
method: "GET",
success:function (response) {
$scope.employees = response["Name"];
}
});
}
});
I do also have the ng directives on the desired page:
<div class="container" ng-app="AWEmpApp" ng-controller="AWEmpControl">
{{employees}}
</div>
I tested to see if the scripts work fine by assigning $scope.employees = "Hello..."; and no problems, so I know it has nothing to do with script loading.... What could be the issue? I've made sure to describe the request as GET and to return a JSON object. Am I missing something?
Thanks in advance.
EDIT
I checked the firefox console and got back Parsing Error: No XML found at location.......
Which I found odd since the server returns a JSON object, so I replaced the ajax method with the following:
function loadEmployees() {
$http.get('/AWEmployee/Index/GetEmployees')
.then(function(response) {
$scope.employees =response;
});
};
Now response is html data of the page that called it (Index), instead of the JSON object ! I assume something is happening in between the communication as suggested in this post.
As you use JQuery to fetch data from server instead of $http service and moreover success function is executed asynchronous, AngularJS will not reflect any changes that was happened, to force it, just wrap assigning into $apply:
function loadEmployees() {
$.ajax({
url: "/AWEmployee/Index/GetEmployees",
method: "GET",
success:function (response) {
$scope.$apply(function(){
$scope.employees = response["Name"];
});
}
});
}
Found out the issue, it's a simple mistake on my part. I was calling http://localhost:53729/AWEmployees/Index/GetEmployees which was the wrong thing to do. I took out the Index page, so now the url looks like http://localhost:53729/AWEmployees/GetEmployees and it worked perfectly!

Multiple jQuery Ajax calls in a Backbone App mixes data up

I work on a Backbone app with a collection for data sources. Whenever a new data source is added, its model is added to the collection, and a jQuery Ajax call is made for it like this:
fetch: function() {
var model = this,
url = model.get("url");
function testCallback(parObj) {
return function(data, textStatus, jqXHR) {
alert("test - "+parObj.url+" : "+data.sourceurl);
}
}
$.ajax({
url: url,
type: "GET",
dataType: "jsonp",
jsonpCallback: "data",
success: testCallback({ model: model, url: url })
})
.done(function (data) {
alert("done - "+model.get("url")+" : "+data.sourceurl);
});
}
The fetch() is called in rapid succession, and debugging it I can see everything is ok when I initiate the Ajax request.
Everything works great if I only add two data sources.
But both the done() and testCallBack() functions mixes up the data when I have three requests running simultaneously on three different domains (same happens in both Chrome and Safari).
For instance:
URL 1 gets the data from URL 1.
URL 2 gets the data from URL 3.
URL 3 gets the data from URL 2.
Am I doing something wrong? Any help is greatly appreciated.
That's because you're setting the jsonpCallback parameter to the same thing for each request. Just remove that line entirely as jQuery will automatically create unique ones for you.

Posting data and params using $resource using angularjs

I have a angular service which has custom methods like this
appServices.factory('RuleSets', ['$resource',
function($resource){
return $resource('', {}, {
query: {
method:'GET',
isArray:true,
url: '../data/routing-ruleset-:ruleSetId.json'
},
unschedule: {
method: 'POST',
url: '../data/unschedule:ruleSetId.json'
},
schedule: {
method: 'POST',
params: {ruleSetId: ':ruleSetId', date: ':date'},
url: '../data/schedule.json'
}
});
}]);
I am having issues posting data using my custom methods
RuleSets.unschedule({ruleSetId: ruleSetId});
and
RuleSets.schedule({date: $scope.formattedDate, ruleSetId: $scope.selectedRuleSet})
The behavior i see int he former is that the ruleSetId url parameter does not get populated if it is a POST request. In the latter, I do not know how to populate the request parameters if it is a post request (I am aware the code written is incorrect), as what I have tried in my services function does not work. I would also like to send data as part of the request to 'schedule'. I have seen how I can do this by say doing this
var ruleSets = new RuleSets();
ruleSets.id = $scope.selectedRuleSet
ruleSets.$save();
but how do I do it with a custom method?
Should I rather be using $http or not so many custom methods. I like the structure that custom methods provides, so i'd like to keep it like that if possible.

Categories