how can call json web services in angular js - javascript

Webservices url
http://3.srsm-s.appspot.com/trailerScreenOld.php?title=TWFhbiBLYXJhdGU=&_movie_id_=MjIlk4MTU3OA==&year=MjlmxNA==&seckey=g96c1n1m#
Js code
var web = angular.module('web',[]);
web.controller('webcont', function($scope,$http)
{
$http.get("http://3.srsm-s.appspot.com/trailerScreenOld.php?title=TWFhbiBLYXJhdGU=&_movie_id_=MjIlk4MTU3OA==&year=MjlmxNA==&seckey=g96c1n1m#").success(function(response)
{
$scope.names = response.movie;
}
);
});
As tried but the service is not loading and not displaying the data
it throws some error
such us
Page not found
request not initialized

I don't know so much about the service you connect but load the link in the browse to get the response on and see the result.
{"success":0,"message":"Oops SomeThing Went Wrong."}
Maybe that's the problem

Related

Server rendering with AngularJS

i'm developing a webapp in AngularJS (1.5) and Flask, and i'm self-taught.
My webapplication is not public, so any resource is reserved.
In the first version i manage rendering of the pages by AngularJS through ngRoute and resolve, but i've understood that is a mistake.
In the second version i'm changing the rendering of the page from Angular to Flask, but every time i've the same problem: Flask render a page, send it to Angular but Angular doesn't show it but instead it show the template in the routing. I've try many cases:
render the login page with Angular and serve just a controller to call the server and load the server rendered page;
render all with Flask and just a controller in Angular to manage the auth
use the resolve instead a function in controller for manage the reserved page
For each case i've the same situation: server response with html rendered page, but it's not showed by Angular.
I've found some solutions about my problems: upgrade to Angular2.0 or implement Node.JS, or implement angular-server ... but i would like to avoid to add other components and understand what's wrong.
Part of the Angular routing code
var reserved = {
name: "reserved",
params: {aaa:true} }
var reservedContent = {
name: "reserved.content",
url: "/reserved",
template: "<h1>Angular rendered</h1>" }
and in app.run
$transitions.onBefore({ to: 'reserved.*' }, function(t){
var AuthService = t.injector().get('appAuth');
var authorization = appAuth.authorization(t.to().url.substr(1), $rootScope.token);
authorization.then(function() {
$rootScope.resource = t.to().url;
pySrv.app($rootScope.resource)
.then(function(data){
console.log("The html server rendered page: " + data);
console.log("The Angular template in state" + t.to().template);
t.to().template = data;
},
function(data){
console.log("Reject"); } );
},
function(){
$state.target("403"); }); });
I always see "Angular rendered" in the page.

loading data from json files

Im trying to figure something out. If I want to load JSON data from a local file in my angular app, is there a way for me to include or to read the file in angular, or do I need to use some file API to read from the file and store the objects in a array. ty
you can use $http for loading json data from json file
var name = angular.module("app", []);
name.controller("ctrlu", ['$scope','$http', function($scope, $http)
{
$http.get('js/data.json').success (function(data){
$scope.guitarVariable = data;
});
}]
);
Note:you don't need to include(reference) json file in index.html page

Can $http.put write data to JSON file

I apologize for the newbie question but I am getting conflicting answers to this while searching on the net.
I have created an AngularJS app to read from a JSON file using $http.get and display the data as a form with each form element binded with ng-model. Ideally I would like the user to be able to edit the desired field and click save, then have that data updated in the JSON file. I have been told that to do this you will need a 3rd party server like NodeJS, but I am seeing other examples that show it being done in videos. Can someone tell me if this is possible without the 3rd party server and if so what is the best practice for doing this.
Thank you
$http GET (for resource located on client) will not work with the Chrome browser and will give a CORS error (unless you disable Chrome web security by opening Chrome using run .../chrome.exe" --allow-file-access-from-files -disable-web-security). Firefox gives an error saying the JSON in not well formed even though it is. Browsers don't seem to like it.
HTML5 LocalStorage is your best bet for client storage where you wish to perform CRUD operations and have the data survive past page refresh. A good example of this is the [TodoMVC example]
(https://github.com/tastejs/todomvc/tree/gh-pages/architecture-examples/angularjs)
A very simple example that saves a json file to localstorage and reads the contents of localstorage is shown. The Service contains a getter and a setter method to interact with localstorage.
INDEX.HTML
<body ng-app = "app">
<div ng-controller="MainCtrl">
<form>
<input placeholder="Enter Name.." ng-model="newContact"/>
<button type="submit" class="btn btn-primary btn-lg"
ng-click="addContact(newContact)">Add
</button>
</form>
<div ng-repeat="contact in contacts track by $index">
{{contact.name}}
</div>
</div>
APP.JS
angular.module('app', ['app.services'] )
.controller('MainCtrl', function ($scope, html5LocalStorage) {
//create variable to hold the JSON
var contacts = $scope.contacts = html5LocalStorage.get();
$scope.addContact = function(contact) {
$scope.contacts.push( {"name":contact} ); //Add new value
html5LocalStorage.put($scope.contacts); //save contacts to local storeage
}
});
SERVICES.JS
angular.module('app.services', [] )
.factory('html5LocalStorage', function () {
var STORAGE_ID = 'localStorageWith_nG_KEY'; //the Local storage Key
return {
//Get the localstorage value
get: function ()
{
return JSON.parse(localStorage.getItem(STORAGE_ID) || '[]');
},
//Set the localstorage Value
put: function (values)
{
localStorage.setItem(STORAGE_ID, JSON.stringify(values));
}
};
});
Otherwise you could use Node and Express and store the JSON file on the server. Use file system module 'fs-extra' to interact with the json file.
You would have to create RESTful API routes for the client to interact with the server using $http and perform CRUD operations.
/put
/get
/delete
/post
I would be interested to see these videos of this being done without the server writing to the file. You cant just "post the .json file" and have it replace the old one, unless you configure your server (apache, nginx, tomcat, node) to do so.

Reading and writing to a server-side file in AngularJS

I'm attempting to create a simple guestbook with AngularJS, and read and write the names to a simple file. Trouble is, I can't seem to get my code to even read from the file.
This is my directory structure:
This is index.html:
<!DOCTYPE html>
<html ng-app>
<head>
<meta charset="ISO-8859-1">
<title>GuestBook</title>
<script src="http://code.angularjs.org/angular-1.0.0rc3.min.js"></script>
<script type="text/javascript" src="javascript/user.js"></script>
</head>
<body>
<h1>Welcome!</h1>
<div ng-controller="UserCtrl">
<ul class="unstyled">
<li ng-repeat="user in users">
{{user}}
</li>
</ul>
</div>
</body>
</html>
This is user.js (Based off this question/answer):
function UserCtrl($scope) {
$scope.users = $(function() {
$.get('data/users', function(data) {
var array = data.split(',');
console.log(array);
});
});
}
And this is my users file:
John,Jacob,James
I'm expecting this outcome:
Welcome!
John
Jacob
James
But instead, all I get is:
Welcome!
So my question is, how can I populate $scope.users with the names in the users file?
I know I've got my AngularJS set up correctly because I was able to get the desired result when I hard-coded it:
$scope.users =[John,Jacob,James];
I've also spent a lot of time googling and searching Stack Overflow for how to read and write to a file with JavaScript and/or AngularJS, but:
No one seems to be trying to do exactly what I'm trying to do;The instructions are either confusing or not really applicable to what I'm trying to do.
I'm also not sure where to begin to write code that will persist names to the users file -- but I'll be happy if I can just read the file for now, and ask how to write to it later in a separate question. (But extra gratitude if you do also show me how to write to it.)
Try injecting angular's $http service into your controller first of all. And make sure you add a '/' before your 'data/users' path. (/data/users)
function UserCtrl($scope, $http) {
$scope.users = [];
$http.get('/data/users')
.success(function(data, status, headers, config) {
if (data && status === 200) {
$scope.users = data.split(',');
console.log($scope.users);
}
});
});
}
You can check your console to see what kind of data is being returned. (Network tab)
edit: just realized the $(function ... part didn't make sense.
The problem with your code is in this stub -
$scope.users = $(function() {
$.get('data/users', function(data) {
var array = data.split(',');
console.log(array);
});
});
Here $scope.users is not the array variable. Instead, it is whatever $() returns.
Your anonymous function is passed only as a parameter to $ function.
Rewrite your controller this way -
function UserCtrl($scope, $http) {
$scope.users = [] // Initialize with an empty array
$http.get('data/users').success(function(data, status, headers, config) {
// When the request is successful, add value to $scope.users
$scope.users = data.split(',')
})
}
And now, since you have
<li ng-repeat="user in users">
{{user}}
</li>
in your view, angular will set up a watch on $scope.users variable.
If the value of $scope.users changes anytime in the future, angular will automatically
update the view.
EDIT -
Along with the above edit, you need to make sure all the files are being served via a web server on the same host:port. Browsers limit AJAX access to another domain:port. Here is a quick way to do start a http server -
Go to the project directory using terminal and type in
python -m SimpleHTTPServer for python
or
ruby -run -e httpd -- -p 8000 . for ruby.
Both will start a basic HTTP server at port 8000, serving content from that particular directory. Having done this, your index.html will be at http://localhost:8000/index.html and your data file should be accessibe as http://localhost:8000/data/user.js (your javascript can still use /data/user.js).
It turns out I can't do what I'm trying to do the way I'm trying to do it. JavaScript by itself can't read files on the Server-Side, only on the Client-Side. To read and persist data, JavaScript has to make calls to a "Back-end" or server, written in something like Java, which isn't just a Browser scripting language.
you entered 'users' instead of 'users.txt' as filename.
This works just fine to me:
function UserCtrl($scope, $http) {
$scope.users = []
$http.get('data/users.txt').success(function(data, status, headers, config) {
$scope.users = data.split(',')
})}

How to call json rest service in html through dojo

I am developing an maven web application using rest web services. I am trying to call the simple web service from the dojo. But I did not know getting started to call rest service through dojo. My web service code is:
#GET
#Path("/users")
#Produces("application/json")
public ArrayList dynamicFetch() {
ArrayList<User> ar = new ArrayList<User>();
User u1 = new User(1,"Test",30);
ar.add(u1);
u1 = new User(2,"test2",31);
ar.add(u1);
return ar;
}
Which executes and shows
[{"age":30,"name":"Test","id":1},{"age":31,"name":"test2","id":2}]
How can i call this json object in html through dojo since all my elements are dojo..?
Please Help any help will be apprciated more
Thanks
Prior to dojo v1.7, try this:
dojo.xhrGet({
url: "/users",
handleAs:"json",
load: function (data) {
// data is the array object it responds.
console.log(data);
}
});
See the Dojo Ajax reference guide for details.

Categories