HTTP request with angularJS - html

I'm trying to make an HTTP request from AngularJS v1.5.8 but it does not work.
I have a simple HTML form and a submit button that calls my login() function:
<body ng-app="myApp" ng-controller="loginController">
......
......
......
<div
class="col-md-4 col-md-offset-4 col-sm-4 col-sm-offset-3 col-xs-6 col-xs-offset-3">
<button type="submit" class="btn btn-default" ng-submit="login()">Submit</button>
</div>
And this is my loginController
var app = angular.module ("myApp", []);
app.controller("loginController", function($scope, $http){
$scope.username = "";
$scope.password = "";
$scope.login = function() {
$http(
{
method : 'POST',
url : SessionService.getserverName()+'/RestServices/services/login/add',
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
},
data : {
username : $scope.username,
password : $scope.password
}
}).success(function(response, status) {
if (response.result.success && status == 200) {
$log.info('OK');
$location.path('/newPage.html');
}
})
}
});
The HTTP request does not really run.

ngSubmit attribute work only on form element. see https://docs.angularjs.org/api/ng/directive/ngSubmit.
Try to move
ng-submit="login()"
to your form element

Try with using the structure below ..
$http({
url: 'put url here',
method: "put action here just like GET/POST",
data: { 'name': 'Rizwan Jamal' }
})
.then(function (resp) {
//TODO: put success logic here
},
function (resp) {
//TODO: put failed logic here
}
);
.then() method fires in both the success and failure cases. The then() method takes two arguments a success and an error callback which will be called with a response object.
NOTE :
If you are not using form validation so please change ng-submit with ng-click.. I hope this solution will work for You :)

app.js
'use strict';
// Declare app level module which depends on filters, and services
var app= angular.module('myApp', ['ngRoute','angularUtils.directives.dirPagination','ngLoadingSpinner']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'loginCtrl'});
$routeProvider.when('/home', {templateUrl: 'partials/home.html', controller: 'homeCtrl'});
$routeProvider.when('/salesnew', {templateUrl: 'partials/salesnew.html', controller: 'salesnewCtrl'});
$routeProvider.when('/salesview', {templateUrl: 'partials/salesview.html', controller: 'salesviewCtrl'});
$routeProvider.when('/users', {templateUrl: 'partials/users.html', controller: 'usersCtrl'});
$routeProvider.when('/forgot', {templateUrl: 'partials/forgot.html', controller: 'forgotCtrl'});
$routeProvider.otherwise({redirectTo: '/login'});
}]);
app.run(function($rootScope, $location, loginService){
var routespermission=['/home']; //route that require login
var salesnew=['/salesnew'];
var salesview=['/salesview'];
var users=['/users'];
$rootScope.$on('$routeChangeStart', function(){
if( routespermission.indexOf($location.path()) !=-1
|| salesview.indexOf($location.path()) !=-1
|| salesnew.indexOf($location.path()) !=-1
|| users.indexOf($location.path()) !=-1)
{
var connected=loginService.islogged();
connected.then(function(msg){
if(!msg.data)
{
$location.path('/login');
}
});
}
});
});
loginServices.js
'use strict';
app.factory('loginService',function($http, $location, sessionService){
return{
login:function(data,scope){
var $promise=$http.post('data/user.php',data); //send data to user.php
$promise.then(function(msg){
var uid=msg.data;
if(uid){
scope.msgtxt='Correct information';
sessionService.set('uid',uid);
$location.path('/home');
}
else {
scope.msgtxt='incorrect information';
$location.path('/login');
}
});
},
logout:function(){
sessionService.destroy('uid');
$location.path('/login');
},
islogged:function(){
var $checkSessionServer=$http.post('data/check_session.php');
return $checkSessionServer;
/*
if(sessionService.get('user')) return true;
else return false;
*/
}
}
});
sessionServices.js
'use strict';
app.factory('sessionService', ['$http', function($http){
return{
set:function(key,value){
return sessionStorage.setItem(key,value);
},
get:function(key){
return sessionStorage.getItem(key);
},
destroy:function(key){
$http.post('data/destroy_session.php');
return sessionStorage.removeItem(key);
}
};
}])
loginCtrl.js
'use strict';
app.controller('loginCtrl', ['$scope','loginService', function ($scope,loginService) {
$scope.msgtxt='';
$scope.login=function(data){
loginService.login(data,$scope); //call login service
};
}]);

Related

How to call jsonp api using $http in angularjs

// this is service where i m calling api
app.factory('users',['$http','$q', function($http , $q) {
return {
getUsers: function() {
var deferred = $q.defer();
var url = 'http://www.geognos.com/api/en/countries/info/all.jsonp?callback=JSONP_CALLBACK';
$http.jsonp(url).success(function (data, status, headers, config) {
console.log(data);
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
//this always gets called
console.log(status);
deferred.reject(status);
});
return deferred.promise;
}
}
}]);
//this is my controller where i calling getUsers();
app.controller('myCtrl', function($scope, users) {
$scope.data = users.getUsers();
})
while calling it gives me error
Uncaught ReferenceError: callback is not defined(anonymous function)
Plz give me proper solution so that i can see me api data in <div>. Thanks in advance
$http already returns a promise. There is no need to form a promise of a promise. Try this:
app.factory('Users', ["$http", function($http){
return {
getUsers: function(url) {
return $http({
url: url,
method: 'JSONP'
});
}
};
}]);
Controller:
app.controller("MyCtrl", ["$scope", "Users", function($scope, Users) {
$scope.data = [];
Users.getUsers('http://www.geognos.com/api/en/countries/info/all.jsonp?callback=JSONP_CALLBACK').then(function(response){
console.log(response.data);
$scope.data = response.data;
}).catch(function(response){
console.log(response.statusText);
});
}]);
Here the scenario is a bit different as you have to declare a $window.callback function.
Code
var app = angular.module("demoApp", []);
app.factory('UserService', ['$http', function ($http, $q) {
var getUsers = function () {
var url = 'http://www.geognos.com/api/en/countries/info/all.jsonp?callback=callback';
return $http.jsonp(url);
};
return {
GetUsers: getUsers
}
}]);
app.controller("demoController",
["$scope", "$window", "UserService",
function ($scope, $window, UserService){
UserService.GetUsers();
$window.callback = function (response) {
$scope.countries = response.Results;
}
}]);
Plunkr: http://plnkr.co/edit/MFVpj1sMqJpcDg3ZwQFb?p=preview

AngularJS Cannot read property 'getData' of undefined in VS

do you know what I am doing wrong? I want to read data from my json-file but i got the error that it canĀ“t read the property getData.
myApp.service('jsonDataService', function ($http) {
this.getData = function () {
return $http({
method: 'GET',
url: '/jsonData/Stations.json'
});
}
});
controller:
myApp.controller('IndexController', ['$scope', function ($scope, jsonDataService) {
jsonDataService.getData().then(function (msg) {
$scope.msg = msg;
console.log(msg);
});
}]);
I am using ng in Visual studio in a mvc project.
path json-file: " Visual Studio 2015\Projects\Test\WebApplication\Scripts\jsonData\Stations.json"
In the controller code which you have shared, you have not injected 'jsonDataService' service properly.
It should be:
myApp.controller('IndexController', ['$scope', 'jsonDataService', function ($scope, jsonDataService) {
jsonDataService.getData().then(function (msg) {
$scope.msg = msg;
console.log(msg);
});
}]);

AngularJS : Factory JSON Array with HTTP GET

I'm developing my first AngularJS app using the Google Docs API to pass it JSON data.
This is an example of the factory I'm using:
app.factory('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
return {
news:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/1/public/values?alt=json', {cache: true});
},
updates:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/2/public/values?alt=json', {cache: true});
},
docs:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/3/public/values?alt=json', {cache: true});
}
}]);
I wanted to clean up a bit the code and decided to use services instead of making the calls in the controller itself. It works normally, but it's a pain in the ass the fact that I still need to write long $scopes because of the structure of the Google API. This is how I get the values in the controller:
app.controller('homeCt', ['$scope', 'Data', function ($scope, Data){
Data.news().success(function (data) {
$scope.totalNews = data.feed.entry.length;
});
}]);
Is there a way that I can set the factory service to pass me the data just using:
$scope.totalNews = Data.news()
Or at least removing the 'feed.entry'?
Data.news().success(function (data) {
$scope.totalNews = data.length;
});
Thank you very much!
example of service - resolve the success with the data you want
app.service('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
this.news =function(){
return $http.get(googleDocs + apiKeys.googleDoc +'/1/public/values? alt=json', {cache: true})
.then(function(data){
return data.feed.entry.length;
});
}
}]);
the controller - since you already resolved the data in service hence..
app.controller('homeCt', ['$scope', 'Data', function ($scope, Data){
Data.news().then(function (data) {
$scope.totalNews = data;
});
}]);
working example
var app = angular.module('app', ['ionic'])
.service('Data', ['$http',
function($http) {
var googleDocs = 'https://spreadsheets.google.com/feeds/list/1aC1lUSxKatfxMKEy1erKDSAKgijSWOh77FDvKWhpwfg/1/public/values?alt=json';
this.news = function() {
return $http.get(googleDocs, {
cache: true
}).then(function(res) {
return res.data.feed.entry;
});
}
}
])
.controller('homeCt', ['$scope', 'Data',
function($scope, Data) {
Data.news().then(function(data) {
console.log(data);
})
}
]);
I'll give you a way of doing it, a way that I don't recommend at all (a service should not handle the scope), but for me it is the only way you have if you don't want to destroy the "async" of your ajax call :
app.factory('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
return {
news:news,
updates: updates,
[...]
}
function news(scopeValue) {
$http.get(googleDocs + apiKeys.googleDoc +'/1/public/values?alt=json', {cache: true}).success(function(data){
scopeValue = data;
});
}]);
and then, call it that way in your controller :
Data.news($scope.totalNews);

What does Error: [$injector:unpr] Unknown provider: tProvider <- t <- myActiveLinkDirective mean?

Basically I am testing to see how a PROD version of my app is looking; I proceeded to run it through some gulp tasks (minify, strip unused css etc.) and got this error:
Error: [$injector:unpr] Unknown provider: tProvider <- t <- myActiveLinkDirective
Can anyone help with what's going on here?
This is some my angular code:
var rustyApp = angular.module('rustyApp', [
'ngAnimate',
'ngRoute',
'viewController',
'mm.foundation',
'angular-flexslider',
'ui.router']).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
title: 'home',
templateUrl: '/partials/home.html',
controller: 'HomeController'
}).when('/work', {
title: 'my work',
templateUrl: '/partials/work.html',
controller: 'WorkController'
}).when('/contact', {
title: 'contact',
templateUrl: '/partials/contact.html',
controller: 'ContactController'
}).otherwise({redirectTo: '/'});
// configure html5 to get links working
$locationProvider.html5Mode(true);
}]);
rustyApp.controller('BasicSliderCtrl', function($scope) {
$scope.slides = [
'../images/sliderContent/1.jpg',
'../images/sliderContent/2.jpg',
'../images/sliderContent/3.jpg',
'../images/sliderContent/4.jpg'
];
});
rustyApp.run(function() {
FastClick.attach(document.body);
});
rustyApp.run(['$location', '$rootScope', function($location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', function(event, current, previous) {
$rootScope.title = current.$$route.title;
});
}]);
rustyApp.controller('HomeController', function($scope) {
$scope.pageClass = 'home';
});
rustyApp.controller('WorkController', function($scope) {
$scope.pageClass = 'work';
});
rustyApp.controller('ContactController', function($scope) {
$scope.pageClass = 'contact';
});
rustyApp.controller('OffCanvasDemoCtrl', function($scope) {});
var OffCanvasDemoCtrl = function($scope) {};
rustyApp.controller('ContactController', function($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method: 'POST',
url: '../partials/mailer.php',
data: $.param($scope.formData), //param method from jQuery
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} //set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result = 'bg-success';
if ($scope.result === 'bg-success') {
$scope.class = "bg-success";
}
// if($scope.result){setTimeout(window.location.reload(true),4000);}
if ($scope.result) {
setTimeout(function() {
window.location.reload(true)
}, 4000);
}
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result = 'bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
if ($scope.submitButtonDisabled) {
$scope.class = "bg-danger";
}
$scope.resultMessage = 'Failed Please fill out all the fields.';
$scope.result = 'bg-danger';
}
}
});
var viewController = angular.module('viewController', []);
rustyApp.directive('myActiveLink', function($location) {
return {
restrict: 'A',
scope: {
path: "#myActiveLink"
},
link: function(scope, element, attributes) {
scope.$on('$locationChangeSuccess', function() {
if ($location.path() === scope.path) {
element.addClass('uk-active');
} else {
element.removeClass('uk-active');
}
});
}
};
});
// var $j = jQuery.noConflict();
// $j(function() {
// $j('#Container').mixItUp();
// });
rustyApp.directive('mixItUp', function() {
var directive = {
restrict: 'A',
link: link
};
return directive;
function link(scope, element, attrs) {
var $j = jQuery.noConflict();
var mixContainer = $j('#Container');
mixContainer.mixItUp();
mixContainer.on('$destroy', function() {
mixContainer.mixItUp('destroy');
});
}
});
rustyApp.directive('share', function() {
var directive = {
restrict: 'A',
link: link
};
return directive;
function link(scope, element, attrs) {
var $s = jQuery.noConflict();
// mixContainer.on('$destroy', function() {
// mixContainer.mixItUp('destroy');
// });
var $s = new Share(".share-button", {
networks: {
facebook: {
app_id: "602752456409826",
}
}
});
}
});
rustyApp.directive('animationOverlay', function() {
var directive = {
restrict: 'A',
link: link
};
return directive;
function link(scope, element, attrs) {
var modal = $.UIkit.modal(".modalSelector");
if (modal.isActive()) {
modal.hide();
} else {
modal.show();
}
}
});
UPDATED CODE
var rustyApp = angular.module('rustyApp', [
'ngAnimate',
'ngRoute',
'viewController',
'mm.foundation',
'angular-flexslider',
'ui.router'
]).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
title: 'home',
templateUrl: '/partials/home.html',
controller: 'HomeController'
}).when('/work', {
title: 'my work',
templateUrl: '/partials/work.html',
controller: 'WorkController'
}).when('/contact', {
title: 'contact',
templateUrl: '/partials/contact.html',
controller: 'ContactController'
}).otherwise({redirectTo: '/'});
// configure html5 to get links working
$locationProvider.html5Mode(true);
}]);
rustyApp.controller('BasicSliderCtrl', ['$scope',
function($scope) {
$scope.slides = [
'../images/sliderContent/1.jpg',
'../images/sliderContent/2.jpg',
'../images/sliderContent/3.jpg',
'../images/sliderContent/4.jpg'
];
}]);
rustyApp.run(function() {
FastClick.attach(document.body);
});
rustyApp.run(['$location', '$rootScope', function($location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', function(event, current, previous) {
$rootScope.title = current.$$route.title;
});
}]);
rustyApp.controller('HomeController', ['$scope', function($scope) {
$scope.pageClass = 'home';
}]);
rustyApp.controller('WorkController', ['$scope', function($scope) {
$scope.pageClass = 'work';
}]);
rustyApp.controller('ContactController', ['$scope', function($scope) {
$scope.pageClass = 'contact';
}]);
rustyApp.controller('OffCanvasDemoCtrl', ['$scope', function($scope) {}]);
var OffCanvasDemoCtrl = function($scope) {};
rustyApp.controller('ContactController', ['$scope', function($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method: 'POST',
url: '../partials/mailer.php',
data: $.param($scope.formData), //param method from jQuery
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} //set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result = 'bg-success';
if ($scope.result === 'bg-success') {
$scope.class = "bg-success";
}
// if($scope.result){setTimeout(window.location.reload(true),4000);}
if ($scope.result) {
setTimeout(function() {
window.location.reload(true)
}, 4000);
}
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result = 'bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
if ($scope.submitButtonDisabled) {
$scope.class = "bg-danger";
}
$scope.resultMessage = 'Failed Please fill out all the fields.';
$scope.result = 'bg-danger';
}
}
}]);
var viewController = angular.module('viewController', []);
rustyApp.directive('myActiveLink', ['$location', function($location) {
return {
restrict: 'A',
scope: {
path: "#myActiveLink"
},
link: function(scope, element, attributes) {
scope.$on('$locationChangeSuccess', function() {
if ($location.path() === scope.path) {
element.addClass('uk-active');
} else {
element.removeClass('uk-active');
}
});
}
};
}]);
// var $j = jQuery.noConflict();
// $j(function() {
// $j('#Container').mixItUp();
// });
rustyApp.directive('mixItUp', function() {
var directive = {
restrict: 'A',
link: link
};
return directive;
function link(scope, element, attrs) {
var $j = jQuery.noConflict();
var mixContainer = $j('#Container');
mixContainer.mixItUp();
mixContainer.on('$destroy', function() {
mixContainer.mixItUp('destroy');
});
}
});
rustyApp.directive('share', function() {
var directive = {
restrict: 'A',
link: link
};
return directive;
function link(scope, element, attrs) {
var $s = jQuery.noConflict();
// mixContainer.on('$destroy', function() {
// mixContainer.mixItUp('destroy');
// });
var $s = new Share(".share-button", {
networks: {
facebook: {
app_id: "602752456409826",
}
}
});
}
});
rustyApp.directive('animationOverlay', function() {
var directive = {
restrict: 'A',
link: link
};
return directive;
function link(scope, element, attrs) {
var modal = $.UIkit.modal(".modalSelector");
if (modal.isActive()) {
modal.hide();
} else {
modal.show();
}
}
});
UPDATE
So I wound using gulp-ng-annotateand it appears to add the syntax which was suggested below :) However when I try a PROD build I don't get any errors or anything, it just fails silently. Can anyone help?
I posted the generic answer below before I had a chance to see the rest of the code you posted. Yes, indeed you have some controllers and directives that use inference. Change your code to use inline annotation, the $inject property; or less intrusively, use a tool like ng-annotate (thanks #deitch for the pointer).
If you're minifying your code, don't use the inference style of dependency annotation. Use the $inject property or use inline annotation. See https://docs.angularjs.org/api/auto/service/$injector.
Example
Don't rely on inference:
function ($scope, $timeout, myFooService) {
}
Use either inline annotation:
[ '$scope', '$timeout', 'myFooService', function ($scope, $rootScope, myFooService) {
}]
Or the $inject property:
function MyFactory($scope, $timeout, myFooService) {
}
MyFactory.$inject = [ '$scope', '$timeout', 'myFooService' ];
This is because the inference flavour relies on the argument names of the function to be preserved (and match to existing services). You might be losing the original names during minification.
Set mangle: false.
This setting solved same problem that I had.
var $ = require('gulp-load-plugins')();
$.uglify({
mangle: false,
compress:true,
output: {
beautify: false
}
});

How to load more than one json file in angular

I am wondering how to load multiple .json files in to template.
In my example I have submissions from users and I do not want to store everything in one json file if possible.
How to grab some data from multiple json files?
here is my plunk example
I want to load users.json as well
var app = angular.module('myApp', []);
app.directive('contentItem', function ($compile,$parse) {
templates = {
image: 'image.html',
event: 'event.html',
article: 'article.html',
ad: 'ad.html',
discount: 'discount.html',
video: 'video.html'
}
var linker = function(scope, element, attrs) {
scope.setUrl = function(){
return templates[scope.content.content_type];
}
}
return {
restrict: "E",
replace: true,
link: linker,
scope: {
content: '='
},
templateUrl: 'main.html'
};
});
function ContentCtrl($scope, $http) {
"use strict";
$scope.url = 'content.json';
$scope.content = [];
$scope.fetchContent = function() {
$http.get($scope.url).then(function(result){
$scope.content = result.data;
});
}
$scope.fetchContent();
}
Help appreciated
You can request for JSON either from the controller like:
app.controller('myController', function($scope, $http){
$scope.users = [];
$scope.getUsers = function() {
$http({method: 'JSONP', url: "users.json?query=?callback=JSON_CALLBACK&query="+ $scope.searchString}).
success(function(data, status) {
$scope.users = data;
}).
error(function(data, status) {
console.log(data || "Request failed");
});
};
and the other approach (better one) would be to make use of angular factory to fetch the JSON file.
myApp.factory('getUsersFactory',['$http',function($http){
return {
getUsers: function(callback){
$http({method: 'JSONP', url: "users.json?query=?callback=JSON_CALLBACK&query="+ $scope.searchString}).success(callback);
}
}
}]);
where now you can include this factory as a dependency and get the user data and assign that in the callback function.