Error: $ is not defined (Angularjs ) - angularjs

When i call submit function it calls but give error like this , what is the error in this function .
Error: $ is not defined
$scope.submit#http://localhost/angularAjax/app.js:19:21
Mc/u/<#https://code.angularjs.org/1.0.3/angular.min.js:70:297
dc[c]</</</<#https://code.angularjs.org/1.0.3/angular.min.js:140:1
Sc/this.$get</e.prototype.$eval#https://code.angularjs.org/1.0.3/angular.min.js:86:306
Sc/this.$get</e.prototype.$apply#https://code.angularjs.org/1.0.3/angular.min.js:86:412
dc[c]</</<#https://code.angularjs.org/1.0.3/angular.min.js:140:505
pc/c/<#https://code.angularjs.org/1.0.3/angular.min.js:22:460
m#https://code.angularjs.org/1.0.3/angular.min.js:6:191
pc/c#https://code.angularjs.org/1.0.3/angular.min.js:22:433
Here is code :
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
$scope.hello = {name: "Boaz"};
$scope.newName = "";
/*$scope.sendPost = function() {
var data = $.param({
json: JSON.stringify({
name: $scope.newName
})
});
$http.post("/echo/json/", data).success(function(data, status) {
$scope.hello = data;
})
} */
$scope.submit = function () {
$http({
method : 'POST',
url : 'pro.php',
data : $.param($scope.contact), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
}) .success(function (data) {
alert(data);
console.log(data);
});
}
});
Angular is working , just ajax call fails

The $.param function you are calling inside $scope.submit is from jQuery. Make sure you are including a reference to jQuery in your page

i think you can convert the data to json, using JSON.stringify like this:
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
$scope.hello = {name: "Boaz"};
$scope.newName = "";
/*$scope.sendPost = function() {
var data = $.param({
json: JSON.stringify({
name: $scope.newName
})
});
$http.post("/echo/json/", data).success(function(data, status) {
$scope.hello = data;
})
} */
$scope.submit = function () {
$http({
method : 'POST',
url : 'pro.php',
data : JSON.stringify($scope.contact), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
}) .success(function (data) {
alert(data);
console.log(data);
});
}
});

Related

how to pass http data from service to controller in angularjs

var locationListCtrl=function($scope, loc8rData){
$scope.message = "Searching for nearby places";
loc8rData
.success(function(data){$scope.message = data.length > 0 ? "" : "No locations Found";
$scope.data = { locations: data };
})
.error(function(e){
$scope.message = "Sorry, Something has gone wrong";
console.log(e);
});
};
var loc8rData = function ($http){
return $http.get('/api/locations?lng=33.7741195&lat=-13.9626121&maxDistance=20');
};
Some points:
take into consideration, when you received one response from $http it's the common response (with status, headers, etc). So, if you want to access your data you will have to do: response.data
Usually, when you have a service, you define multiple endpoints. So, you can return an object with multiple requests.
Check this little sample working: https://plnkr.co/edit/FNxEeVZti6D1wmLe
.service('PokeApi', function($http) {
return ({
getPokemon: function (name) {
return $http({
method: 'GET',
url: 'https://pokeapi.co/api/v2/pokemon/' + name,
headers: { 'Content-Type': 'application/json' }
});
}
})
})
And the controller is as simple as:
.controller('MainCtrl', function($scope, PokeApi) {
$scope.name = 'Plunker';
PokeApi.getPokemon('pikachu').then(function (response) {
$scope.pokemon = response.data;
});
});

return a value from $get factory method when calling service from controller in AngularJs

Im trying to call service from controller which gives me below error..
Provider 'loginService' must return a value from $get factory method.
Below is my code.What is that im doing wrong.
CONTROLLLER CODE
app.controller('loginController', ['$scope', '$http', 'loginService', function ($scope, $http, loginService) {
$scope.checkdata = function () {
var userName = $scope.username;
var password = $scope.password;
//Call the login service
loginService.validateUser(userName, password);
alert(response.data);
}
}])
Service code
app.factory('loginService', function ($http) {
this.validateUser = function (userName, password) {
var userData = new Object();
userData.userName = userName;//Data.username;
userData.password = password;//Data.password;
return $http({
url: "http://localhost:53181/api/User",
dataType: 'json',
method: 'POST',
data: userData,
headers: {
"Content-Type": "application/json"
}
}).then(function (response) {
alert(response);
if (response.data && response.data.data && response.data.data.length == 1)
return response.data.data[0];
});
}
});
Create service funtcion like this:
yourAPICallingFuntion: function() {
var url = "your url";
var deferred = $q.defer();
$http.get(url, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(function(data) {
deferred.resolve(data.data);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
In Controller Call like this:
loginService.yourAPICallingFuntion().then(function(data){
//Now this will give you response in form of data
//you can this data according to your requirement
});
factory service is expected to return a value from factory function. It doesn't have this context (it's either window or undefined).
If you want to use this like this.validateUser = ..., use service service instead.

Not able to get unique response from a factory method called in two different controllers

I am trying to call a factory to generate token from two different controllers
1.homeCtrl
2.savingsCtrl
but m getting same token value in both places
here is my code
---factory
app.factory('tokenFactory', ['$http', function($http) {
return $http({
method: 'POST',
url: "../api/v1/getToken",
headers : {
'Content-Type':'application/json',
'X-API-KEY':'04g4g00c04ks4sokgkoosg0kwww0cww4www0kc80',
'Authorization':"Basic cGVzYXZlQXBwOkNDNTVzV0FwUW0zYWxpazlLNTcwTTFXQ1RNOUJ1TmZS"
},
data: {"grant_type":"client_credentials"}
}) .success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
----homeCtrl
app.controller('homeCtrl', ['$scope','tokenFactory', function($scope,tokenFactory){
tokenFactory.success(function(data) {
$scope.token = data;
var token=data.access_token;
}])
----savingsCtrl
app.controller('savingsCtrl', ['$scope','tokenFactory','savingsFactory', function($scope,tokenFactory,savingsFactory){
tokenFactory.success(function(data) {
$scope.token = data;
var token=data.access_token;
var userId='9c28735e-8a29-401d-b94e-6cc90a087d96';
alert(token)
$scope.getGoals=function(){
savingsFactory.getGoals(userId,token).success(function(data) {
$scope.goals = data;
var goal=$scope.goals.goalName;
alert(goal)
});
}
You should return the $http with some method not directly in factory
app.factory('tokenFactory', ['$http', function($http) {
var getToken = function(){
return $http({
method: 'POST',
url: "../api/v1/getToken",
headers : {
'Content-Type':'application/json',
'X-API-KEY':'04g4g00c04ks4sokgkoosg0kwww0cww4www0kc80',
'Authorization':"Basic cGVzYXZlQXBwOkNDNTVzV0FwUW0zYWxpazlLNTcwTTFXQ1RNOUJ1TmZS"
},
data: {"grant_type":"client_credentials"}
}) .success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}
return {
getToken : getToken
}
}]);
and then use it in controllers like this
tokenFactory.getToken().then(function (data) {
$scope.token = data.data.access_token;
var token = data.data.access_token;
alert(token);
});
I have tested this and its working
Try this:
----factory
app.factory('tokenFactory', ['$http', function($http) {
function getToken() {
$http({
method: 'POST',
url: "../api/v1/getToken",
headers : {
'Content-Type':'application/json',
'X-API-KEY':'04g4g00c04ks4sokgkoosg0kwww0cww4www0kc80',
'Authorization':"Basic cGVzYXZlQXBwOkNDNTVzV0FwUW0zYWxpazlLNTcwTTFXQ1RNOUJ1TmZS"
},
data: {"grant_type":"client_credentials"}
})
}
return {getToken: getToken}
}]);
----homeCtrl
app.controller('homeCtrl', ['$scope','tokenFactory', function($scope,tokenFactory){
tokenFactory.getToken()
.success(function(data) {
$scope.token = data;
var token=data.access_token;
}
}])
----savingsCtrl
app.controller('savingsCtrl', ['$scope','tokenFactory','savingsFactory', function($scope,tokenFactory,savingsFactory){
tokenFactory.getToken()
.success(function(data) {
$scope.token = data;
var token=data.access_token;
var userId='9c28735e-8a29-401d-b94e-6cc90a087d96';
alert(token)
$scope.getGoals=function(){
savingsFactory.getGoals(userId,token).success(function(data) {
$scope.goals = data;
var goal=$scope.goals.goalName;
alert(goal)
});
}
}])

Angularjs how pass Multiple parameters and header values

Error
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the
var myApp = angular.module("myApp", []);
myApp.controller('TestingCtrl', function ($scope, $http) {
var GetData = function () {
$http({
method: "GET",
url: 'http://103.22.11.11/Buses/Sources'
}).success(function (response) {
$scope.Return = response.Id[0];
alert("ddd");
})
}
GetData();
})
how can i pass this headers
'ConsumerKey': '811D72785AC287ACE3E8',
'ConsumerSecret': 'C80A758DCC6BCEBE436D25BC'
Did you try like below.
var myApp = angular.module("myApp", []);
myApp.controller('TestingCtrl', function ($scope, $http) {
var GetData = function () {
$http({
method: "GET",
url: 'http://103.22.11.11/Buses/Sources',
data:{'dummy':'dummy'},
headers: {'Content-Type':'application/json',
'ConsumerKey': '811D72785AC287ACE3E8',
'ConsumerSecret': 'C80A758DCC6BCEBE436D25BC'}
}).success(function (response) {
$scope.Return = response.Id[0];
alert("ddd");
})
}
GetData();
});

AngularJS defer return until completed

I have tried to build a service that will return a $resource after the service has authenticated.
I have done it like this:
.factory('MoltinApi', ['$q', '$resource', '$http', 'moltin_options', 'moltin_auth', function ($q, $resource, $http, options, authData) {
var api = $resource(options.url + options.version + '/:path', {
path: '#path'
});
var authenticate = function () {
if (!options.publicKey)
return;
var deferred = $q.defer();
var request = {
method: 'POST',
url: options.url + 'oauth/access_token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: "grant_type=implicit&client_id=" + options.publicKey
};
$http(request).success(function (response) {
authData = response;
deferred.resolve(api);
});
return deferred.promise;
};
return authenticate();
}])
But I can not call the resource in my controller:
.controller('HomeController', ['MoltinApi', function (moltin) {
var self = this;
moltin.get({ path: 'categories' }, function (categories) {
console.log(categories);
});
}]);
it just states that 'undefined is not a function'.
Can someone tell me what I am doing wrong?
Update 1
So after playing with the solution that was suggested, this is the outcome.
angular.module('moltin', ['ngCookies'])
// ---
// SERVICES.
// ---
.factory('MoltinApi', ['$cookies', '$q', '$resource', '$http', 'moltin_options', function ($cookies, $q, $resource, $http, options) {
var api = $resource(options.url + options.version + '/:path', {
path: '#path'
});
var authenticate = function () {
if (!options.publicKey)
return;
var deferred = $q.defer();
var authData = angular.fromJson($cookies.authData);
if (!authData) {
console.log('from api');
var request = {
method: 'POST',
url: options.url + 'oauth/access_token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: "grant_type=implicit&client_id=" + options.publicKey
};
deferred.resolve($http(request).success(function (response) {
$cookies.authData = angular.toJson(response);
setHeaders(response.access_token);
}));
} else {
console.log('from cookie');
deferred.resolve(setHeaders(authData.access_token));
}
return deferred.promise;
};
var setHeaders = function (token) {
$http.defaults.headers.common['Authorization'] = 'Bearer ' + token;
}
return authenticate().then(function (response) {
return api;
});
}]);
and to call it I have to do this:
.controller('HomeController', ['MoltinApi', function (moltin) {
var self = this;
moltin.then(function (api) {
api.get({ path: 'categories' }, function (categories) {
console.log(categories);
self.sports = categories.result;
});
});
}]);
but what I would like to do is this:
.controller('HomeController', ['MoltinApi', function (moltin) {
var self = this;
moltin.get({ path: 'categories' }, function (categories) {
console.log(categories);
}, function (error) {
console.log(error);
});
}]);
As you can see, the service is checking to see if we have authenticated before returning the API. Once it has authenticated then the API is returned and the user can then call the api without having to authenticate again.
Can someone help me refactor this service so I can call it without having to moltin.then()?
You are returning the authenticate function call in the MoltinApi factory, so you are returning the promise. And the method get doesn't exist in the promise

Resources