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.
Related
I am passing an array of values through POST method dynamically.
If i pass more than 50 array values, i am not able to process those data.
I am getting error 505.
I browsed and found that it is an Http error, which refers the post size is not good here.
So i added the properties in my jboss configuarion,
</system-properties>
<property name="org.apache.tomcat.util.http.Parameters.MAX_COUNT" value="-1"/>
</system-properties>
Even after this, i am not able to pass array value more than 50.
Please give some solution for this.
This is my code, in Restfull webservice, where i get data from angular controller.
this.updateConstraint = function($scope, $location, $routeParams) {
var url = hostName + "/dcr/rest/capacityfile/searchcf/blockC/addSubFilesBlocC";
var listSubFiles = $scope.capacityAddSubFile;
var idCapacity = $routeParams.capacityFileId;
var promise = $http({
url : url,
method : "POST",
params :{ subFileCSF : $scope.capacityAddSubFile,
partConstraint : $scope.selectedPartNumberAndConstraint,
partConstraintAdd : $scope.selectedPartNumberAndConstraintAdd,
capacityFileId : $routeParams.capacityFileId},
}).success(function(data, status, headers) {
}).error(function(data, status, headers) {
// alert("Failed to access"+status+" "+headers);
});
return promise;
};
Here the i am getting error, it is showing error 505.
Please reply.
you need to set max-post-size at connector level.
/subsystem=web/connector=http:write-attribute(name=max-post-size, value=80)
I want to construct a mechanism that would access a database via POST requests. So far, I do received the desired data, but am have issues with the timing. Here are three pieces of code that I'm using (simplified to keep the focus of the question).
First, a factory handling the HTTP request vis-à-vis a servlet:
var My_Web = angular.module('My_Web');
My_Web.factory('DB_Services', function($http , $q) {
var l_Result ;
var DB_Services = function(p_Query) {
var deferred = $q.defer();
var url = "http://localhost:8080/demo/servlets/servlet/Test_ui?";
var params = "data=" + p_Query ;
var Sending = url + params ;
$http.post(Sending).
success(function(data, status, headers, config) {
deferred.resolve(data);
}).
error(function(data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
return DB_Services;
});
Second, a general purpose function handling the promise (or so I meant) exposed to all the controllers that would need to extract data from the remote DB:
$rootScope.Get_Data_from_DB = function(p_Query) {
DB_Services(p_Query).then(function(d) {
console.log("In Get_Data_from_DB; Received data is: " + JSON.stringify(d));
$scope.data = d;
});
};
Third, one example within one of the controllers:
$scope.Search_Lookups = function () {
console.log ("search for lookup data...") ;
var l_Lookup_Type = document.getElementById("THISONE").value ;
var l_Send_Request_Data = '{"Requestor_ID":"4321" , "Request_Details" : { "Data_type" : "' + l_Lookup_Type + '" } }' ;
console.log("Sending Request: " + l_Send_Request_Data) ;
l_Data = $rootScope.Get_Data_from_DB(p_Query) ;
console.log ("Received response: " + l_Data) ;
Deploy_data(l_Data) ;
}
The function Deploy_data(l_Data) is responsible of dismembering the received data and put the relevant pieces on screen.
What happens is that I get on the console the string Received response: undefined and immediately after the result of the retrieval as In Get_Data_from_DB; Received data is: (here I get the data).
The Received response: undefined is printed from the invoking function (third piece of code), whereas the output with the actual data is received and printed from within the second piece of code above. This means that the invocation to Deploy_data would not receive the extracted data.
Once again, the same mechanism (i.e. the factory $rootScope.Get_Data_from_DB) would be vastly used by many controllers.
I thought of using $scope.$watch but I'm not sure because the same user might be triggering several queries at the same time (e.g. request a report that might take few seconds to arrive and, in the meantime, ask for something else).
I think I found a solution (at least it appears to be ok for the time being). The global function Get_Data_from_DB accepts a second parameter which is a callback of the invoking controller.
The invoking controller creates a private instance of the Get_Data_from_DB function and triggers a request providing the callback function.
I'll need to test this with parallel queries, but that is still a long way to go...
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'm developing a single page application. I am making use of Angularjs.v1.2.28. I'm making a HTTP GET request to the backend using this code.
return {
getCategories : function(sessionid,terminalid,tableno,section){
var req = {
method: 'GET',
url: Config.url+ "/menucategories",
params : {
'sessionid' : sessionid,
'terminalid' : terminalid,
'tableno' : tableno,
'section' : section
}
};
return $http.get(req);
},
I make use of the promise object that is returned from service in controller.
var categoryPromise = categoryService.getCategories(sessionid,terminalid,tableno,section);
categoryPromise.then(function(payload){
var categories = payload.data;
if(categories.status.code == "1"){
if(Object.prototype.toString.call(categories) === '[object Array]') {
$scope.categories = categories;
categoryService.setCategories(categories);
$scope.pax = tableService.getPax();
$scope.tablechair = tableService.getChoseTableChair();
}
}
else{
$location.url("/login");
$scope.errorMsg = categories.status.desc;
}
},function(errorPayload){
$location.url("/login");
$scope.errorMsg = "Server error while processing the request.Please contact system administrator";
});
It's always the errorCallback is getting called due to the URL getting changed to the browser application URL appended with some malformed characters. The URL which i give is
http://localhost:8080/CafexRestful/menucategories
But, it gets changed to the browser application URL below
http://localhost:8080/CafexMobile/[object%20Object]
I have been debugging in Chrome and Firebug. I couldn't resolve it. It may be something which is happening under the hood. The same code is working with another controller and service, where i fetch a different data. Please let me know if you need anymore information. Thanks.
$http.get in angularjs needs an url string. You should use url string instead of an object
Using $http.get function:
return {
getCategories : function(){
return $http.get("/menucategories"); // using $http.get function.
},
Using $http function.
return {
getCategories : function(sessionid,terminalid,tableno,section){
var req = {
method: 'GET',
url: Config.url+ "/menucategories",
params : {
'sessionid' : sessionid,
'terminalid' : terminalid,
'tableno' : tableno,
'section' : section
}
};
return $http(req); //using $http function only.
},
Please see the document: https://docs.angularjs.org/api/ng/service/$http
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();
});