When making a http jsonp request, the returned json or xml object always causes the browser to output
Unexpected token ':'. Parse error.
Or in the case of xml
Unexpected token '<'. Parse error.
This is my code.
For cross origin purposes, jsonp is needed. Even the existing examples seem to have trouble with certain sites like the one provided here.
Whereas a link such as http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero, which also requires cross origin request, works flawlessly.
Please tell me what I might be doing wrong and how to resolve this issue, thanks.
app.factory('service', function($q, $http, $templateCache) {
return {
getHistoricalData: function(symbol, start, end) {
var deferred = $q.defer();
var format = '&format=json&callback=JSON_CALLBACK';
var query = 'id=UxxajLWwzqY';
var url = 'http://ytapi.gitnol.com/get.php?' + query + format;
$http.jsonp(url)
.success(function(json) {
var quotes = json;
console.log(json); //need to see some results here
deferred.resolve(quotes);
});
return deferred.promise;
}
};
});
app.controller('ContentCtrl', function($scope, service) {
$scope.getData = function() {
var promise = service.getHistoricalData($scope.symbol, $scope.startDate, $scope.endDate);
promise.then(function(data) {
$scope.items = data;
});
};
$scope.getData();
});
Related
This question already has answers here:
Loading cross-domain endpoint with AJAX
(9 answers)
Closed 5 years ago.
I am trying to get URL using zillow api in angular JS.
angular.module('account.settings').controller('AccountSettingsCtrl', ['$scope', '$http', '$sce',
function($scope, $http, $sce) {
var getZillowURL = function() {
var url = "http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=X1-ZWz1ft20wfj30r_94p25&address=2114+Bigelow+Ave&citystatezip=Seattle%2C+WA";
var trustedUrl = $sce.trustAsResourceUrl(url);
$http.jsonp(trustedUrl, {
jsonpCallbackParam: 'callback'
})
.success(function(result) {
$scope.mortgageLocation = result;
console.log('success!');
console.log(result);
})
.error(function(data, status) {
console.log('error!');
console.log(data);
});
};
getZillowURL();
}
]);
But JSONP returns error.
When I access with the URL which is used as JSONP parameter, webbrowser shows correctly.
This zillow API returns XML data.
How can I get this as a JSON type data?
You can use xml2json. get it from here :
xml2json github
Add a refrance :
<script src="xml2json.js"></script>
and in your controller, after you get the xml response from api convert it to json like this
var x2js = new X2JS();
var jsonResponse= x2js.xml_str2json(your_xml);
Please find below the angularjs factory method to call http request:
var HttpService = angular.module("HttpService",[]);
HttpService.factory("HttpServiceFactory",['$http', '$q', '$location', '$rootScope' ,function($http, $q, $location, $rootScope){
return {
getData: function(url, headers, bOnErrorRedirect, bShowInPageError, params){
var headerParam = {'Accept':'application/json'};
if(headers !== undefined || headers !== null){
headerParam = $.extend(headerParam, headers);
}
var updatedParams = {'TimeStamp':new Date().getTime()};
updatedParams = $.extend(params, updatedParams);
var deferred = $q.defer();
$http.get(url,{
headers: headerParam,
params : updatedParams
}).success(function(successResponse){
if(successResponse){
var responseJSON = angular.fromJson(successResponse);
if(responseJSON && responseJSON.messages && responseJSON.messages.length){
//Process Error
}else{
deferred.resolve(successResponse);
}
}else{
deferred.resolve(successResponse);
}
}).error(function(errorResponse , status){
//Process Error
console.error("status here:: "+status);
});
return deferred.promise;
}
}
}]);
And I am calling this method in controller with all required dependencies as below:
HttpServiceFactory.getData(args.sURL,null,false,true,args.oQueryParams).then(function(response){
scope.bDataLoading = false;
// process data
})
.catch(function(oResponse) {
scope.bDataLoading = false;
scope.bDisplayError = true;
// process error
});
Here everything works fine. But the issue is when I've multiple http calls on a page, the UI freezes and does not allow to interact till the request has been processed.
For example, on a page I am displaying 2 angular-ui-grid based on user's selected criteria by input box and calendar control. In such case, the UI freezes until both grids have been displayed or error message has been displayed.
During http service call, user can not do anything but simply wait to finish the request.
How do I resolve the issue of UI freezing ? Is it a true async behavior ? If not, what am I missing to achieve correct async behavior ?
I am trying to use the Forecast.io weather API to build a weather application with Ionic. I am having a hell of a time getting the AJAX response data delivered to my controller for use in my view.
My Factory Service:
.factory('WeatherService', function($cordovaGeolocation) {
var posOptions = { timeout: 10000, enableHighAccuracy: false };
return {
// Get current Geolocation position with the configured /posOptions/
getPosition : $cordovaGeolocation.getCurrentPosition(posOptions),
// Query the result of /getPosition/ for /lat/, /long/, and /accuracy/
getCoords : function(pos) {
var loc = {
lat : pos.coords.latitude,
long : pos.coords.longitude,
accuracy : pos.coords.accuracy
};
return loc;
},
// Build the API request URI
getApi : function(lat, long) {
var url = 'https://api.forecast.io/forecast/';
var apiKey = 'foo';
var forecastApi = url + apiKey + '/' + lat + ',' + long + '?callback=?';
return forecastApi;
},
// Execute a request against the API URI to recieve forecast data
getForecast : function(api) {
var forecast;
$.ajax({
url : api,
dataType : 'json',
async : false,
success : function(res) {
forecast = res;
}
});
return forecast;
}
};
})
My Controller Method:
.controller('DashCtrl', function($scope, WeatherService) {
WeatherService.getPosition.then(function(pos) {
var pos = pos;
return pos;
}).then(function(pos) {
var coords = WeatherService.getCoords(pos);
return coords;
}).then(function(coords) {
var api = WeatherService.getApi(coords.lat, coords.long);
return api;
}).then(function(api) {
$scope.forecast = WeatherService.getForecast(api);
console.log($scope.forecast);
});
})
There's probably a lot of things inherently wrong with the above code. From my reading I have been made aware that then() methods really shouldn't be used in the controller method, and all of that logic should be isolated to the Service Method. I will be refactoring to that pattern when I get this working.
I am using the jQuery $.ajax() instead of $http because of CORS issues with Forecast.io when developing locally. $jsonp was throwing syntax errors on the response, so I had to resort to jQuery for the call to get this working locally.
I know I am getting a successful response because if I console.log(forecast) inside the $.ajax call I can explore the weather data. For whatever reason, I am unable to save the response value to the forecast var saved in the parent scope of the ajax call and then return that to the controller for use in my view with the $scope.forecast variable. It is always returning undefined.
I have looked at plenty of SO questions while trying to get this working on my own, and have yet to have any success..
How do I return the response from an asynchronous call?
Get Data from a callback and save it to a variable in AngularJS
Well, if you really really feel the need to use ajax (probably better to track down and fix the jsonp issue) then you should probably wrap the forcast in your very own promise.
.factory('WeatherService', function($q,$cordovaGeolocation) {
...
getForecast : function(api)
{
var deferred = $q.defer();
$.ajax({url : api, dataType : 'json', async : false,
success : function(res) {
defereed.resolve(res);
}
});
return defereed.promise;
}
You already know how to handle promises in your controller code so I won't post those changes.
I am new to angular and what I am willing to do is replace a piece of code I wrote in the past in jquery to angularjs.
The goal is to take a string from a span element, split it in two and pass the two strings as parameters in a GET request.
I am trying to learn best coding pratices and improving myself so any comments of any kind are always welcome.
Working Code in jquery:
//Get Song and Artists
setInterval(function () {
var data = $('#songPlaying').text();
var arr = data.split('-');
var artist = arr[0];
var songTitle = arr[1];
//Request Lyrics
$.get('lyricsRequester.php', { "song_author": artist, "song_name" : songTitle},
function(returnedData){
console.log(returnedData);
$('#refreshLyrics').html(returnedData);
});
},10000);
Code in Angular
var app = angular.module("myApp", []);
app.factory('lyricService', function($http) {
return {
getLyrics: function($scope) {
//$scope.songArr = $scope.currentSong.split('-'); <-- **undefined currentSong**
//$scope.artist = $scope.songArr[0];
//$scope.songTitle = $scope.songArr[1];
return
$http.get('/lyricsRequester.php', {
params: {
song_author: $scope.artist,
song_name: $scope.songTitle
}
}).then(function(result) {
return result.data;
});
}
}
});
app.controller('lyricsController', function($scope, lyricService, $interval) {
$interval(function(){
lyricService.getLyrics().then(function(lyrics) {
$scope.lyrics = lyrics; <-- **TypeError: Cannot read property 'then' of undefined**
console.log($scope.lyrics);
});
}, 10000);
});
index.html (just a part)
<div class="col-md-4" ng-controller="lyricsController">{{lyrics}}</div>
<div class="col-md-4"><h3><span id="currentSong" ng-model="currentSong"></span></h3><div>
You need to be careful with your return statement when used in conjunction with newlines, in these lines:
return
$http.get('/lyricsRequester.php',
If you don't, JS will automatically add a semicolon after your return, and the function will return undefined.
Move the $http.get statement to the same line as your return statement.
return $http.get('/lyricsRequester.php', ...
Refer to the following docs:
MDN return statement
Automatic Semicolon Insertion
As for your second issue, you $scope is not really something you inject into your services (like $http). Scopes are available for use in controllers.
You need to refactor your code a bit to make things work.
eg. Your getLyrics function can take a song as a parameter. Then in your controller, you call lyricsService.getLyrics(someSong). Scope access and manipulation are only done in your controller.
app.factory('lyricService', function($http) {
return {
getLyrics: function(song) {
var songArr = song.split('-');
var artist = songArr[0];
var songTitle = songArr[1];
return $http.get('/lyricsRequester.php', {
params: {
song_author: artist,
song_name: songTitle
}
}).then(function(result) {
return result.data;
});
}
}
});
app.controller('lyricsController', function($scope, lyricService) {
$scope.currentSong = 'Judas Priest - A Touch of Evil';
$interval(function(){
lyricService.getLyrics($scope.currentSong).then(function(lyrics) {
$scope.lyrics = lyrics;
console.log($scope.lyrics);
});
}, 10000);
});
You also have some other issues, like using ng-model on your span. ng-model is an angular directive that is used in conjunction with form elements (input, select etc.), not a span as you have. So you might want to change that into an input field.
$http does not use .then, it uses .success and .error. the line that you have where it says then is undefined, should be replaced with a success and error handler instead. Below is a sample from the docs:
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
See Link:
https://docs.angularjs.org/api/ng/service/$http
My first time with http request. I use Angular for it. Server works normal - it's public news API. I need to get JSON file by URL like "hostname.com/article/2014/06/10/123?api-key=1234567890".
function Ctrl($scope, $http, $templateCache) {
//some code there
$scope.load_article = function( patch ) {
$http.get(patch + "?" + $scope.apikey)
.success(function(response){
result = angular.fromJson(response.data);
$scope.article = result;
}).error(function(response) {
$scope.article = "error "+ response.status;
});
};
}
But when i call load_article() tracer shows me that result:
Method: OPTIONS;
Status: 596 OK;
Type: text/xml;
and "error undefined" into $scope.article.
Where is my fault?
Upd:
$http.jsonp(patch + "?" + $scope.apikey).success(function(data)){...}
Will be better for get JSON file.
JSONP usually requires you to send a callback function in your request (you should look up the documentation for the api). If you'd tell us what public news API you're using, someone might help.