AngularJS issue (POST 405 Method Not Allowed) - javascript

I am new to Angular. I am learning about the $http service and currently trying to send JSON data via POST. Unfortunately, I am getting an error. I tried reading other people's posts concerning this problem, but I can't seem to understand what the issue is.
Can anyone help me understand why I am getting this error and suggest ways of fixing it ?
HTML
<!DOCTYPE html>
<html ng-app = "app">
<head>
<title></title>
</head>
<body ng-controller = "ctrl">
<form>
<input type="text" ng-model = "newDJ_name">
<button ng-click = "addDJ(newDJ_name)">Add new DJ name</button>
<button ng-click = "show()">Show DJs</button>
</form>
<div ng-repeat = "dj in djs">
{{dj.name}}
</div>
</body>
<script src = "angular.min.js"></script>
<script src = "httpService.js"></script>
</html>
Javascript
var app = angular.module ("app",[]);
app.controller ("ctrl",function ($scope,$http) {
$scope.show = function () {
$http.get('djs.json').success(function(data){
$scope.djs = data;
})
};
$scope.addDJ = function (newName) {
$http.post('http://localhost:8080/Documents/Angular/djs.json',{name : newName})
.success(function(data) {
$scope.djs = data;
})
.error (function(data) {
console.log(":(");
})
}
});
JSON file
[{
"name": "Adam Beyer",
"city": "Sweden",
"genre": "techno",
"label": "Drumcode"
}, {
"name": "Richie Hawtin",
"city": "Detroit",
"genre": "techno",
"label": "Minus"
}, {
"name": "Solomun",
"city": "Undefined",
"genre": "techno",
"label": "Dyinamic"
}]
When I try to add a new dj name

You are trying to make POST your data directly to a .json file. This is not possible.
Instead, write a webservice endpoint on your server that:
-Accepts the 'POST' phrase and payload data
-Writes the data to a file, in your case, a .JSON file
-Returns a meaningful response back to your Angular app, based on the success or failure of creating the file.
Note - if you are trying to update a .JSON file that already contains data, you will probably need to parse the existing file as JSON, mutate it with the new data, then save it back to the file.
If you were to change the webservice phrase to GET, you should typically see a successful response:
// This will work
$http.get('http://localhost:8080/Documents/Angular/djs.json')

Related

How to prevent DOM from loading until object is fully loaded into $scope?

I am loading a JSON that is almost 19,000 lines...minified to a single line its about 240k. I am loading it into my app via index.html file as a global var:
<script type="text/javascript" src="js/cdjson.js"></script>
var _countries = {
"country": {
"USA": {
"currency": {
"currencyCode":["USD"],
"currencyName":["United States Dollar"],
"currencySymbol":["$"]
},
"info": {
...
...
},
"phone" : {
...
},
"postal" : {
...
}
},
"CAN" : {
...
}
}
}
In the the controller its being assigned to a $scope variable $scope.countries = _countries.country ;. However, when the html DOM for that controller loads its trying to access the $scope variable before before the object is fully loaded into the $scope causing JS object errors like Cannot read property 'country' of undefined.
How can I prevent the page from rendering until the $scope object is fully loaded? The $scope country object is being used in a <select ng-repeat="countries as country">
Ideally your js files should be loaded at the end of your HTML so you dont have this problem. But if that is not an option for you then add this in your controller
$scope.countries = []
angular.element(document).ready(function () {
$scope.countries = _countries.country;
});
and in your HTML
<select ng-if="countries.length" ng-repeat="countries as country">
Have a flag that indicates when the data was fully loaded to the controller.
Something like
<select ng-if="countries.length" ng-repeat="countries as country">

Angular $http using json file works but using json file with $httpBackend is not working to display data

I can fake getting data from json file with using $http but with $resource/ $httpBackend I don't get any results
$http.get (works)
$http.get('api/devices.json')
.then(function (result) {
...//
Above works just fine but the $httpBackend will work with json inline , but not pointing at JSON file
Controller file which calls the deviceResourceMock module
deviceResource.query(function(data) {
vm.devices = data;
});
deviceResourceMock module
app.run(function ($httpBackend) {
var devices = 'test.json'; // Put new json file in same directory
// ABOVE DOES NOT WORK
This DOES work below though
var devices = {"Devices": [
{
"DeviceId": 1,
"DeviceStatus": "Leaf Rake",
"id": "GDN-0011",
"ha": "Leaf rake with 48-inch wooden handle.",
"Urt": "blah"
}
]};
URL and WhenGet
var deviceUrl = "/api/devices";
$httpBackend.whenGET(deviceUrl).respond(devices.Devices);
Thoughts on why it doesn't work?
Is "devices.Devices" function?
I think code should be like
$httpBackend.whenGET(deviceUrl).respond(function(method,url,data) {
return devices.Devices;
});

Parse JSON string values

I have a big problem, I hope somebody can help me solve. I am trying to make a Linkedin sharing function from the API. The content there is in the JSON is postet perfectly on LinkedIn. But the problem is that a person cannot see what there is posted in the posting box. I uploaded my share button to my domain, if somebody wants to test it:
http://www.vouzalis.com/wwwroot/stackTest.html
As I see it, I did everything the API ask:
https://developer.linkedin.com/docs/share-on-linkedin
I cannot see what else I am missing? Does anybody have a clue of what there could be wrong?
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: myAPIKey
authorize: true
onLoad: onLinkedInLoad
lang : da_DK
</script>
</head>
<body>
<script type="in/Share">
</script>
<script>
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", shareContent);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to share content on LinkedIn
function shareContent() {
// Build the JSON payload containing the content to be shared
var payload = {
"comment": "Check this awesome website out",
"content": {
"title": "Hello",
"description": "StackOverflow",
"submitted-url": "https://www.stackoverflow.com",
"submitted-image-url": "http://i.telegraph.co.uk/multimedia/archive/03597/POTD_chick_3597497k.jpg"
},
"visibility": {
"code": "anyone"
}
}
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
};
</script>
</body>
</html>

How do I load JSON objects into separate global variables using AngularJS?

I'm learning AngularJS and I have one JSON file with data that I want to load into separate variables.
My JSON file has two objects/arrays: "views" and "addressbook". I can bind the data to a $scope.variabale in the html but but that's not what i'm looking for. I would like to load the views and addressbook into a "var views" and a "var adressbook" so i can access them with jquery.
My JSON:
{
"myData": {
"views": [
{
"view": "Nieuwe activiteit",
"link": "index.html",
"active": true
},
{
"view": "Activiteiten",
"link": "activiteiten.html",
"active": false
}
],"adresboek": [
{
"Voornaam": "Ruben",
"e-mail": "ruben#e-mail.com",
"mobiel": "0612345678",
"hasFacebook": true,
"hasTwitter": true
},
{
"Voornaam": "Roos",
"e-mail": "roos#e-mail.com",
"mobiel": "0612345677",
"hasFacebook": true,
"hasTwitter": true
}
]
}
}
What i'm trying to get:
var alldata = $http.get('data/data.json').then(function(res) {
var views = res.data.mydata.views;
var adresbook = res.data.mydata.adresbook;
});
I would like to bind the data like so:
$scope.views = alldata.views;
$scope.contacts = alldata.addressbook;
Any help is appreciated :)
Why exactly do you want to put these variables on the global scope/window? This is typically advised against. You may consider creating an Angular Service. A Service allows you to access variables across different modules.
In the context of your code, where is this $http.get request occurring?
EDIT: In response to your comment:
Ok, try something like this?
myApp.controller( 'getData', function($http){
this.onLoad: function(){
$http.get('data/data.json').then(function(res) {
$scope.views = allData.views;
$scope.contacts = allData.addressBook;
}
};
this.onLoad();
};
When you're first instantiating your angular controller it will call the loadData function and set your $scope variables.
(I didn't check your $http code, I just copied what you had down).
You can access the JavaScript global scope at any point by referencing the window object. Make sure to use $apply in angular if you modify data outside off the angular digest. In your example:
var alldata = $http.get('data/data.json').then(function(res) {
window.alldata = {
"views": res.data.mydata.views,
"addressbook": res.data.mydata.adresbook
};
});
You may now access the data in jQuery, e.g.:
console.log( window.alldata.views );

Trying to load local JSON file to show data in a html page using JQuery

Hi I am trying to load local JSON file using JQuery to show data but i am getting some weird error. May i know how to solve this.
<html>
<head>
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$.getJSON( "priorities.json" , function( result ){
alert(result.start.count);
});
});
</script></head>
</html>
I am just alerting the count of JSON data. My JSON file is in the same directory where this html file is and JSON string format is shown below.
{
"start": {
"count": "5",
"title": "start",
"priorities": [
{
"txt": "Work"
},
{
"txt": "Time Sense"
},
{
"txt": "Dicipline"
},
{
"txt": "Confidence"
},
{
"txt": "CrossFunctional"
}
]
}
}
JSON file name priorities.json and error is
Uncaught Referenceerror priorities is not defined
You can simply include a Javascript file in your HTML that declares your JSON object as a variable. Then you can access your JSON data from your global Javascript scope using data.employees, for example.
index.html:
<html>
<head>
</head>
<body>
<script src="data.js"></script>
</body>
</html>
data.js:
var data = {
"start": {
"count": "5",
"title": "start",
"priorities": [{
"txt": "Work"
}, {
"txt": "Time Sense"
}, {
"txt": "Dicipline"
}, {
"txt": "Confidence"
}, {
"txt": "CrossFunctional"
}]
}
}
Due to security issues (same origin policy), javascript access to local files is restricted if without user interaction.
According to https://developer.mozilla.org/en-US/docs/Same-origin_policy_for_file:_URIs:
A file can read another file only if the parent directory of the
originating file is an ancestor directory of the target file.
Imagine a situation when javascript from a website tries to steal your files anywhere in your system without you being aware of. You have to deploy it to a web server. Or try to load it with a script tag. Like this:
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript" language="javascript" src="priorities.json"></script>
<script type="text/javascript">
$(document).ready(function(e) {
alert(jsonObject.start.count);
});
</script>
Your priorities.json file:
var jsonObject = {
"start": {
"count": "5",
"title": "start",
"priorities": [
{
"txt": "Work"
},
{
"txt": "Time Sense"
},
{
"txt": "Dicipline"
},
{
"txt": "Confidence"
},
{
"txt": "CrossFunctional"
}
]
}
}
Or declare a callback function on your page and wrap it like jsonp technique:
<script type="text/javascript" language="javascript" src="jquery-1.8.2.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(e) {
});
function jsonCallback(jsonObject){
alert(jsonObject.start.count);
}
</script>
<script type="text/javascript" language="javascript" src="priorities.json"></script>
Your priorities.json file:
jsonCallback({
"start": {
"count": "5",
"title": "start",
"priorities": [
{
"txt": "Work"
},
{
"txt": "Time Sense"
},
{
"txt": "Dicipline"
},
{
"txt": "Confidence"
},
{
"txt": "CrossFunctional"
}
]
}
})
Using script tag is a similar technique to JSONP, but with this approach it's not so flexible. I recommend deploying it on a web server.
With user interaction, javascript is allowed access to files. That's the case of File API. Using file api, javascript can access files selected by the user from <input type="file"/> or dropped from the desktop to the browser.
As the jQuery API says: "Load JSON-encoded data from the server using a GET HTTP request."
http://api.jquery.com/jQuery.getJSON/
So you cannot load a local file with that function. But as you browse the web then you will see that loading a file from filesystem is really difficult in javascript as the following thread says:
Local file access with javascript
app.js
$("button").click( function() {
$.getJSON( "article.json", function(obj) {
$.each(obj, function(key, value) {
$("ul").append("<li>"+value.name+"'s age is : "+value.age+"</li>");
});
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Tax Calulator</title>
<script src="jquery-3.2.0.min.js" type="text/javascript"></script>
</head>
<body>
<ul></ul>
<button>Users</button>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
article.json
{
"a": {
"name": "Abra",
"age": 125,
"company": "Dabra"
},
"b": {
"name": "Tudak tudak",
"age": 228,
"company": "Dhidak dhidak"
}
}
server.js
var http = require('http');
var fs = require('fs');
function onRequest(request,response){
if(request.method == 'GET' && request.url == '/') {
response.writeHead(200,{"Content-Type":"text/html"});
fs.createReadStream("./index.html").pipe(response);
} else if(request.method == 'GET' && request.url == '/jquery-3.2.0.min.js') {
response.writeHead(200,{"Content-Type":"text/javascript"});
fs.createReadStream("./jquery-3.2.0.min.js").pipe(response);
} else if(request.method == 'GET' && request.url == '/app.js') {
response.writeHead(200,{"Content-Type":"text/javascript"});
fs.createReadStream("./app.js").pipe(response);
}
else if(request.method == 'GET' && request.url == '/article.json') {
response.writeHead(200,{"Content-Type":"text/json"});
fs.createReadStream("./article.json").pipe(response);
}
}
http.createServer(onRequest).listen(2341);
console.log("Server is running ....");
Server.js will run a simple node http server in your local to process the data.
Note don't forget toa dd jQuery library in your folder structure and change the version number accordingly in server.js and index.html
This is my running one https://github.com/surya4/jquery-json.
The d3.js visualization examples I've been replicating on my local machine.. which import .JSON data.. all work fine on Mozilla Firefox browser; and on Chrome I get the cross-origins restrictions error.
It's a weird thing how there's no issue with importing a local javascript file, but try loading a JSON and the browser gets nervous. There should at least be some setting to let the user over-ride it, the way pop-ups are blocked but I get to see an indication and a choice to unblock them.. no reason to be so Orwellian about the matter. Users shouldn't be treated as too naive to know what's best for them.
So I suggest using Firefox browser if you're working locally. And I hope people don't freak out over this and start bombing Mozilla to enforce cross-origin restrictions for local files.
I have Used Following Methods But non of them worked:
// 2 Method Failed
$.get(
'http://www.corsproxy.com/' +
'en.github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
function (response) {
console.log("> ", response);
$("#viewer").html(response);
});
// 3 Method Failed
var jqxhr = $.getJSON( "./json/movies-coming-soon.json", function() {
console.log( "success" );
})
.done(function() {
console.log( "second success" );
})
.fail(function() {
console.log( "error" );
})
.always(function() {
console.log( "complete" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
console.log( "second complete" );
});
// 4 Method Failed
$.ajax({
type: 'POST',
crossDomain: true,
dataType: 'jsonp',
url: 'https://github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
success: function(jsondata){
console.log(jsondata)
}
})
// 5 Method Failed
$.ajax({
url: 'https://github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
headers: { 'Access-Control-Allow-Origin': 'htt://site allowed to access' },
dataType: 'jsonp',
/* etc */
success: function(jsondata){
}
})
What worked For me to simply download chrome extension called "200 OK!" or Web server for chrome and write my code like this:
// Worked After local Web Server
$(document).ready(function () {
$.getJSON('./json/movies-coming-soon.json', function (data) {
var movie_name = '';
var movie_year = '';
$.each(data,function(i,item){
console.log(item.title,item.year,item.poster)
movie_name += item.title + " " + item.year + "<br> <br>"
$('#movie_name').html(movie_name)
})
})
})
Its because you can not access local file without running local web server as per CORS policy so in order to running it you must have some host server.
I would try to save my object as .txt file and then fetch it like this:
$.get('yourJsonFileAsString.txt', function(data) {
console.log( $.parseJSON( data ) );
});

Categories