Okay so I am new to AngularJS, and am trying to get data from an external API. The end result of this is basically going to help me understand angularjs, using external data, some more as well as getting some stats for Call Of Duty Ghosts for my account or others that I search for.
I know that $http.jsonp is the way to go, but the API doesn't really support it as well as CORS... I have accounted for that. I have been able to use jquery to test to make sure I can do it, but am unable to figure it out with AngularJS.
One issue I am having using whateverorigin and anyorigin from https://stackoverflow.com/a/7910570/1888585 and https://stackoverflow.com/a/6104416/1888585 is that I am getting http error 500 (Internal server error)
Without them I am getting an error regarding the json I am getting (which is valid json, checked with json linter) -> 'Uncaught SyntaxError: Unexpected token : '
So here is what I have:
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-controller="GhostsCtrl">
<div id="text">
Data from site: {{getGhostData()}}
Data from site: {{info}}
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.15/angular.js"></script>
<script>
var myApp = angular.module('myApp', []);
var ucdid = "3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c";
var network = "xbl";
var url = "api.codcp.com/user_stats?ucdid="+ucdid+"&network="+network;
var wrapURL = "http://anyorigin.com/get?url="+url+"&callback=?";
var wrapURL4 = 'http://whateverorigin.org/get?url='+url+"&callback=?";
//-----------
myApp.service('dataService', function($http) {
console.log("in service!!");
this.getData = function() {
console.log("http fn");
resp = "test";
// from here i get the syntax error
$http.jsonp("http://"+url+"&callback=JSON_CALLBACK")
.success(function(data) {
console.log("Data gotten");
console.log(data.contents.user);
resp = "Success";
}).error(function(data ) {
console.log("error");
resp = "error";
});
return resp;
}
});
myApp.controller('GhostsCtrl', function($scope, $http, dataService){
$scope.info = null;
$scope.info = dataService.getData();
$scope.getGhostData = function() {
// from here I get the 500 error
delete $http.defaults.headers.common['X-Requested-With'];
$http.jsonp(wrapURL4).success(function(data) {
console.log("success: "+data.contents);
$scope.info = data.contents.user;
}).error(function(data) {
console.log("error: " + data);
});
}
});
</script>
</body>
</html>
And for my jquery code that works just fine:
$.getJSON('http://anyorigin.com/dev/get?url=api.codcp.com/user_stats%3Fucdid%3D3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c%26network%3Dxbl&callback=?', function(data){
$.each(data.contents.user, function(val, idx) {
$("#text span").append(val+" ");
})
console.log(data.contents.user);
});
The json that comes back is as follows:
{"user":{"profile":{"ucdid":"3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c","gamertag":"xNF6xVENGE","network":"xbl","image":"http://avatar.xboxlive.com/avatar/xNF6xVENGE/avatarpic-l.png","kdr":1.109316019930545,"winr":2.7632311977715878,"kill":14694,"deaths":13246,"wins":992,"losses":359,"hoursPlayed":147.32049180327868,"currentStreak":0,"preferredWeapon":"weapon.iw6_arx160"},"squadMember":{"gamertag":"Erskine","xp":1031872,"background":20,"patchbacking":0,"patch":"patch_590","level":57,"nextLevelXp":1070000,"nextLevel":58,"prevLevel":56,"prevLevelXp":1030000,"progress":0.0468,"prestige":6},"careerHistory":{"blackops2prestige":3,"mw3prestige":6,"nextreadblackops2":1405837382,"nextreadmw3":1405841587,"playedblackops2":true,"playedmw3":true},"accounts":["xbl","ucd"],"clan":{"teamId":34018,"name":"xATFWx","memberCount":24,"tag":"ATFW","motto":"Search & destroy ","mottoBg":22,"motd":"","stats":null,"entitlements":268435448,"cxp":1991990,"kdr":1.5,"winp":74,"chat_token":"a2236f048c2a5ab71473b6765909a7f88b8716782dff8fd7b1f9df43b4b2c00ad60ba1e1a47cbea0153f590b89b698de9b91e240a8427fae4a9d8d48ea10d4fe941ab40f62acca0497e3b9c39967621abb9d6c2863ac1935d4fc193b44e2bb19","clanLevel":25,"progress":1,"nextLevelXp":1991990,"cxpNeeded":0,"nextLevel":25,"membership":0,"invited":null}}}
If there is a way I can either call jquery from angularjs easily, or avoid either error I get would be great.
I created a fiddle to figure out what your problem may be and found out that your return statement was getting fired before parsing the data in the service. I have modified the service in order to return a callback and it will work fine.
Since I cannot mock your server request here is sample fiddle and code snippet
myApp.service('dataService', function($http) {
console.log("in service!!");
return {
getData: function(callback) {
console.log("http fn");
resp = "test";
// from here i get the syntax error
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data){
console.log(data.found);
resp="success";
callback(resp);
});
}
}
});
Looks like there are 2 reasons the anyorigin URL is not working.
The URL parameter needs to be properly encoded.
The callback should be JSON_CALLBACK instead of ?
Try this...
var ucdid = "3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c";
var network = "xbl";
var url = "api.codcp.com/user_stats?ucdid="+ucdid+"&network="+network;
var wrapURL = "http://anyorigin.com/get?url=" + encodeURIComponent(url) +"&callback=JSON_CALLBACK";
This should build this URL which properly returns a JSONP response that can be consumed by angular:
http://anyorigin.com/get/?url=api.codcp.com%2Fuser_stats%3Fucdid%3D3f0feb1229202d84b125bab79f7af503ce62057d499ecc0c%26network%3Dxbl&callback=JSON_CALLBACK
See this Fiddle: Live Demo
The jQuery's $.getJSON() is not a jsonp, so if you are able to retrieve the data by $.getJSON(), you could also do it with a normal $http.get() (of course with the use of anyorigin.com).
It seems the api.codcp.com doesn't support JSONP, it response with a normal JSON regardless of a callback=? exists in a url or not.
Fix this for starters, as it is just mixing single and double quote strings in concatenation:
var wrapURL4 = 'http://whateverorigin.org/get?url='+url+"&callback=?";
By the way watch out. He is out there to get you !
Motto:
Search & destroy
and he's armed!
If you have not figured out the jsonp callback in angularjs! here is something that helped me:
$http.jsonp("http://anywebsite.com/?json=get_recent_post&callback=JSON_CALLBACK")
I hope you find this helpful.
jv
Related
There is a web page. In page source have script:
<script>
var important = [{....}];
</script>
How get information from this variable with use node.js???
In a similar situation, when information was in function:
$(function() {
_very.important ([{....}]);
I use code:
var cloudscraper = require("cloudscraper");
cloudscraper.get("link" , function(error, response, data) {
if (error) {
console.log('ERRRRRRROR');
} else {
var info = JSON.parse(data.split("_very.important(")[1].split(")")[0]);
But, I dont know how work with this problem.
var important = [{....}];
You can assign a id to the script like <script id="script"> and get the details through innerHTML like
document.getElementById('script').innerHTML
I get this error
TypeError: self.rooms[setup.to].publish is not a function
when sending the message. I already have the keys in pubnub, what should I do to make it work? My Angular version is 1.6.6.
// Send Messages
$scope.send = function() {
Messages.send({
data: $scope.textbox
});
};
I dunno if you use a form but try this way :
<form name="form" novalidate="true" ng-submit="send()">
$scope.send = function () {
if ($scope.form.$valid) {
var data = $scope.textbox;
$scope.textbox = null;
$scope.messages.push(data);//of push or send depend did proto
}
}
I try to send a handsontable table data using $http POST with Angulars.js
The code below:
var $container = $("div#table");
var handsontable = $container.data('handsontable');
$scope.saveData = function() {
$http.post('save.php', {'data':handsontable.getData()}).success(function(res,status) {
if (res.result === 'ok') {
console.log('Data saved');
}
else {
console.log('Save error');
}
});
}
But I get a 'Save error' with
Undefined index: data in <b>C:\xampp\htdocs\angular\save.php
I the development tool in Chrome I get Request payload of this form:
{"data":[[fdf,gsgg,gsg,null,null,null],[sgsg,sgg,sgg,ggs,null,null]]}
I changed parameters in $http.post to get it work but no solution,
Thank you to give some advices!!!
I finally found a solution in here : [How to retrieve Request Payload
Instead of retrieving the data in this way
$values=$_POST['data'];
I fetch in this way:
$request_body = file_get_contents('php://input');
How can i get data (json format) from another domain?
My problem is: I want to get data from: http://pin-codes.in/api/pincode/400001/
I have tried to use CORS but it didn't work.
My console is:
GET http://pin-codes.in/api/pincode/400001 [HTTP/1.1 200 OK 780ms]
Error Error
My code by client-script:
$(document).ready(function() {
$("#get_data_btn").click(function() {
var data_path = "http://pin-codes.in/api/pincode/400001";
$.getJSON(data_path, null)
.done(function(data) {
console.log("Success: " + data.status);
})
.fail(function(jqxhr, textStatus, error) {
console.log("Error Error");
});
});
});
You probably don't own the other domain right?
No problem at all. Never mind nay-sayers, in computing everything is a yay!
Just use a simple proxy on your server or look into YQL.
this simple query will work:
select * from json where url="http://pin-codes.in/api/pincode/400001/ "
Just test this link (bypassing cross-domain security bull$#!7).
It will get the data you requested as normal plain json (no jsonp) data wrapped in callback-function cbfunc.
Have a look at this question for further info (I did quite a lot of yql scrape answers on SO).
Update:
Here is a crude fiddle demonstrating the whole process: so you enter a url, click fetch and watch the magic happen: http://jsfiddle.net/NbLYE/
function getJSON(url) { //quick and dirty
var script = document.createElement('script');
script.setAttribute('src', url);
script.setAttribute('type', 'text/javascript');
document.getElementsByTagName('head')[0].appendChild(script);
}
function cbfunc(json){ //the callback function
if(json.query.count){
var data=json.query.results.json;
// do your work here, like for example:
//document.getElementById('output').innerHTML=data.toSource();
} else {
alert('Error: nothing found'); return false;
}
}
function fetch(url){ //scrape the url you'd want
var yql="select * " +
" from json" +
" where url='" + url + "';";
yql="http://query.yahooapis.com/v1/public/yql?q=" +
encodeURIComponent(yql) +
"&format=json" +
"&callback=cbfunc";
getJSON(yql);
}
That should get you started (and motivated that it is easy).
Hope this helps!
You don't have the correct CORS headers on your server.
You need to add
Access-Control-Allow-Origin: *
(or something similar) server-side to the response.
Edit: From the HTTP response, it appears you are using PHP. Use the header function in your response.
<?php header('Access-Control-Allow-Origin: *'); ?>
You can't do it using jquery only, you can use any server side script like PHP
Try using php,
<?php
echo file_get_contents('http://pin-codes.in/api/pincode/400001');
?>
Save above code in pincode.php and use jquery like,
$(document).ready(function() {
$("#get_data_btn").click(function() {
var data_path = "pincode.php";
$.getJSON(data_path, null)
.done(function(data) {
console.log("Success: " + data.status);
})
.fail(function(jqxhr, textStatus, error) {
console.log("Error Error");
});
});
});
Also read this
I am using jQuery for a cascading check box, but the getJSON command dosen't work on the server (locally it works fine). It couldn't find the data.json file (see error debug).
Part of the script:
<script type="text/javascript" src="scripts/jquery-1.7.2.js"></script>
<script>
$(function() {
$("#json-one").change(function() {
var $dropdown = $(this);
$.getJSON("data.json?callback=?", function(data) {
var key = $dropdown.val();
var vals = [];
switch(key) {
case 'BR9':
vals = data.BR9.split(",");
break;
case 'base':
vals = ['Please choose from above'];
}
var $jsontwo = $("#json-two");
$jsontwo.empty();
$.each(vals, function(index, value) {
$jsontwo.append("<option>" + value + "</option>");
});
});
});
});
</script>
Error from firebug:
GET http://______my url site ____/data.json 404 NOT FOUND x 25ms
If I change the line
$.getJSON("data.json", function(data) ...
to
$.getJSON("data.json?callback=?", function(data) ...
it doesn't work either.
Can anyone help me?
Have you tried giving the full path to you json file?
$.getJSON("http://www.mywebsite.com/folder/data.json?callback=?", function(data) {});
Is the page you are making JSON call from and the page you are making the call to are on the same domain ? JSON doesn't support cross domain calls and you would need to use JSONP.