Angularjs JSONP not working - angularjs

I might be missing something here but I can't make this JSONP request work, here is the code:
var url = 'http://' + server + '?callback=JSON_CALLBACK';
$http.jsonp(url)
.success(function(data){
console.log('success');
})
.error(function () {
console.log('error')
});
The request fires ok and I am getting the response (with header Content-Type:application/json) in this format:
[{"id": "1", "name": "John Doe"},
{"id": "2", "name": "Lorem ipsum"},
{"id": "3", "name": "Lorem ipsum"}]
Can you see anything wrong? Maybe the format I should return from the server is not right?
Angular fires the error callback without any error message besides the one I set ('error').

#TheHippo is correct the data should not just be a plain json response. Here is a working example of a JSONP request against a youtube endpoint in AngularJS.
A couple of things to note in this example:
Angular's $http.jsonp converts the request querystring parameter from callback=JSON_CALLBACK to callback=angular.callbacks._0.
When calling the youtube endpoint I needed to specify to the service that this is a JSONP request by using alt=json-in-script instead of alt=json in the querystring. This was found in their documentation.
Compare the results of this url to this one to see the difference between JSON and JSONP response in your browser.
Take a look at the Chrome Network Panel in Developer Tools to help compare and troubleshoot with your request/response.
I know this example is very specific but hopefully it helps!

JSONP requires you do wrap your data into a JavaScript function call. So technically you return a JavaScript file and not a Json file.
The data returned from server should similar to this:
// the name should match the one you add to the url
JSON_CALLBACK([
{"id": "1", "name": "John Doe"},
{"id": "2", "name": "Lorem ipsum"},
{"id": "3", "name": "Lorem ipsum"}
]);
Edit: If some one else stumbles across problems with angular's JSONP please also read this answer to this question, it contains usefull informations about how angular handles the actual callback function.

If the response data is "pure" JSON, we can just handle it with angular's $http.get.
$http.get(url).
then(function(response) {
// this callback will be called asynchronously
// when the response is available
$scope.responseArray = response.data;
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Refer to the example on w3schools

Related

JSONP Unexpected Syntax Error (API doesn't support JSONP)

My function:
function getMarketData_() {
$http({
method: 'JSONP',
url: 'https://api.coinmarketcap.com/v2/ticker/',
}).then(function(response) {
console.log('ran');
}).catch(function(response) {
console.log('Error');
});
}
The Error:
Uncaught SyntaxError: Unexpected token :
The location of the error in the returned JSON:
The API doesn't support JSONP.
To test click: https://api.coinmarketcap.com/v2/ticker/?callback=test
An API that supports JSONP would send back something like:
test({
"data": {
"1": {
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"website_slug": "bitcoin",
"rank": 1,
"circulating_supply": 17095362.0,
"total_supply": 17095362.0,
"max_supply": 21000000.0,
"quotes": {
"USD": {
"price": 6530.3,
"volume_24h": 4015800000.0,
"market_cap": 111637842469.0,
"percent_change_1h": -0.66,
"percent_change_24h": -2.31,
"percent_change_7d": -14.6
}
},
"last_updated": 1529097276
}
}
})
For more information, see Wikipedia - JSONP
See also Angular 1.6.3 is not allowing a JSONP request that was allowed in 1.5.8
The API supports CORS.
To test use:
https://www.test-cors.org/#?client_method=GET&client_credentials=false&server_url=https%3A%2F%2Fapi.coinmarketcap.com%2Fv2%2Fticker%2F&server_enable=true&server_status=200&server_credentials=false&server_tabs=remote
This question typically arises when a user attempts to use $http.get and gets:
XMLHttpRequest cannot load https://www.[website].com/ No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4300' is therefore not allowed access.
Then someone suggests $http.jsonp as the workaround. This only works if the API supports JSONP.
For more information, see
XMLHttpRequest cannot load https://www.[website].com/
Why does my JavaScript get a “No 'Access-Control-Allow-Origin' header is present on the requested resource” error when Postman does not?
How to enable CORS in AngularJs
How to use Cors anywhere to reverse proxy and add CORS headers

AngularJS: POST parameters in array notation

My angular.js app posts the following JSON to my backend API:
{"pickupAddress":
{"state":"d","country":"d","city":"d","zipCode":"d","street":"d"},
...}`
Instead of that my backend API required to receive not pickupAddress.state, but pickupAddress[state].
I tried to change the ng-model in my view (to myObject.pickupAddress['country']) but this produces some strange errors.
I want something which results in this (using raw html):
<input type="text" name="pickupAddress[state]" />
The way Angular serializes POST data if you provide an object source is in fact uses not notation your service expects. If instead you use jQuery $.param method to serialize object into param-string and post this string, it should work:
var data = $.param({
"pickupAddress": {
"state": "d",
"country": "d",
"city": "d",
"zipCode": "d",
"street": "d"
}
});
$http.post('test', data, {
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
Above will post data as
pickupAddress[state]:d
pickupAddress[country]:d
pickupAddress[city]:d
pickupAddress[zipCode]:d
pickupAddress[street]:d
Check this discussion in Angular issue page.

AngularJS Chaining $http calls

I am still quite new to AngularJS and struggling to figure the following out.
I have quite a few web-services that I need to use, quite a few of them relies on the data from another to successfully make the next call.
For example, the first web-service will retrieve a list of Profiles.
ip.controller("ProfilesCtrl", function($scope, $http) {
$http.post("Profile_List.asp").success(function(data) {
$scope.profiles = data;
}).error(function() {
alert("An unexpoected error ocurred while loading profiles!");
});
});
Profiles returns a JSON object.
Data returned:
{
"Success": true,
"ErrorMessage": "",
"Objects": [{
"GUID": "208FF69D-A4EB-4760-B2ED-414C900F4AAC",
"Name": "John Doe",
"Status": false
}, {
"GUID": "BC5C53FD-5CA7-4DBE-8594-D26AD88B758B",
"Name": "Jane Doe",
"Status": true
}, {
"GUID": "2FCD677B-DA36-4014-823A-9BDD1A72AD66",
"Name": "Anonymous",
"Status": true
}]
}
Ok, so after I have made the initial call, I need to send the GUID of each Profile Object to another web-service. This service will use the GUID to determine the ID of that specific Profile.
The data from the second web-service will only return the ID for the GUID of the first call.
How can I chain these $http calls? Would it be better to create a new json object and use data from there?
I have done this before using ajax.
*Another question regarding my controller code, is this fine like this or would it be better to maybe do the $http calls as a Service, Provider or Factory? How can I go about doing this?
Any help/links with getting the above to AngularJS code would be appreciated.
Please ask if anything is unclear.
Simply call execute the next call in your "success" handler.
$http.post("Profile_List.asp").success(function(data) {
$scope.profiles = data;
//first call succeeded, and we have the data. call method 2
executeStep2($scope.profiles);
})
function executeStep2(profiles)
{
$http.post("second_method") // etc. (you can just send profiles as post data here)
}

Backbone js. simple error fetching data from the server

I'm new to Backbone, that is why I wrote "simple" in the title, cause this might be an error with a simple solution. I haven't been able to fetch the data from the server and log it.
So, this is the code:
TheModel = Backbone.Model.extend({
urlRoot: '/times/api/day'
});
var nModel = new TheModel({ id:1 });
nModel.fetch();
console.log(nModel.get("minutes"));
The API url is returning a JSON object:
curl http://localhost:7000/times/api/day/1
{"date": "2014-10-25T18:56:32Z", "minutes": 400, "comments": "Tw.Karaoke", "trophy": "", "owner": null}
It doesn't log "400", it logs "undefined", why?.
the fetch operation is asynchronous, so you have to wait till the ajax call is completed
nModel.fetch({
success:function(){
console.log(nModel.get("minutes"));
}});

Retrieve data from a JsonP proxy in sencha touch

I am trying to get the data from a JSONP proxy in sencha touch 2.3(I am using sencha architect 3 to develop). I was successfully able to place jsonp call and get the data back. But I am not getting how to separate every single element of json response. Here is my json Response:-
{"data":[{ "PLANTNUM": "1557", "ROUTEID": "90625", "DELIVERYDATE": "2014-02-12T00:00:00-06:00", "MESCOD": "15", "MESFCT": "DLV", "ORIGID": "HH", "JMSTIME": "02/11/2014 00:11:21", }],"success" : true}
Here is my function
success: function(response){
console.log(response);
var temp=response.data.PLANTNUM;
console.log(temp);
}
I can see below in my console:-
Here is my jsonP request
Ext.data.JsonP.request({
url: 'http://localhost:12608',
callbackKey: 'cbfn',
params: {
method: 'sapout',
type: 'sap',
ordnum: '1034986850'
}
I tried using response.PLANTNUM but that is also not working. It always shows undefined
Can anyone help me out here.
Thanks
data is an array, so you want response.data[0].PLATINUM.

Resources