Using AngularJS, i understand how to fetch JSON data using an AJAX request. This is done as follows:
$http.get('data/parks.json').success(function(data){
$scope.parks = data;
});
However, I am currently storing JSON information within a jQuery Cookie as oppose to in a document on the server, which I need to access using an AJAX request.
The data is stored in the cookie using the following code:
// Add the selected park to the users favourite list
$scope.addFavourite=function(id){
// If user has cookie named userFavourites
if(typeof $.cookie("userFavourites") != "undefined"){
// Turn the cookie data into readable JSON
var favourites = $.parseJSON($.cookie("userFavourites"));
// Filter through the the results of the JSON object and check to see if the result is equal to the selected parks ID
var repeated = favourites.filter(function(a){
return a.id == id
}).length;
// If park is not in the list, add it to the list
if(!repeated){
favourites.push({"id":id});
if($.cookie("userFavourites", JSON.stringify(favourites))){
alertify.success("Successfully added park to favourites");
}
else alertify.eror("Failed to store park in cookie");
}
// Inform the user that the park is already a favourite
else alertify.error("Oops... This park is already in your favourites list!");
}
else{
var favourites = [{ "id":id }];
$.cookie("userFavourites", JSON.stringify(favourites));
alertify.success("Successfully added park to favourites");
}
}
The information adds to the cookie just fine and once I have added some parks into the cookie, when i console.log it I get:
[{"id":1},{"id":2}]
My problem is when I want to fetch the data using AJAX within AngularJS, I'm not sure how to get JSON data from a cookie as oppose to from a file within the folder structures.
I have tried the following but it only returns an error in the console:
$scope.listFavourites=function(){
if(typeof $.cookie("userFavourites") != "undefined"){
$http.get($.cookie("userFavourites")).success(function(data){
$scope.favourites = data;
$scope.totalFavourites = data.length;
});
}
else{
$scope.favourites = "Empty";
}
console.log($scope.favourites);
}
Error:
GET http://www.example.com/angularjs/[%7B%22id%22:1%7D,%7B%22id%22:2%7D] 404 (Not Found)
I have also tried to change the $http.get to $http.jsonp following this documentation (https://docs.angularjs.org/api/ng/service/$http#jsonp) but I haven't had any luck with it.
Any help is appreciated :)
$.cookie("userFavourites")
is all you should need/care about – birdspider Mar 19 at 12:27