I am trying to pass the selected option value calling on the function on change.
<div class="col-md-4">
<select id="mkSelect" ng-model="formData.mk" name="mkSelect" ng-options="mk.MkIdLabel group by mk.FY for mk in mks" ng-change="update()" class="form-control">
</select>
</div>
And in the controller:
$scope.update = function() {
// this displays the MarketId value in the log
console.log($scope.formData.mk.MarketId);
$http({
method: 'POST',
url: 'getMailStatus.php',
// but while trying to send to "getMailStatus.php" it says its undefined
data: $.param($scope.formData.mk.MarketId),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data) {
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
} else {
// if successful, bind success message to message
$scope.message = data.message;
}
});
};
The console.log displays the selected id , but when I try to pass the same using $http it says undefined ($scope.formData.market.MarketID = undefined)
Can anybody point me what i am doing wrong?
$.param needs an object, not a simple value.
http://api.jquery.com/jquery.param/
Try with this:
data: $.param({mkId: $scope.formData.mk.MarketId}),
Related
I'm new to angular js. Here i have the code: I receive the response data like number. In this code how i assign the response data as $scope.vote_counting. In this code does not return anything.
$scope.votes = function(){
var votes = $http({
method: "post",
url: "/getVotes",
data: { id: $scope.Id}
}).success(function(response){
});
return votes;
}
Please anyone help to this.
Simply call the $http. It does not have to be in a function
$http({
method: "post",
url: "/getVotes",
data: { id: $scope.Id }
}).then(function(response) {
//handle success
$scope.votes_counting = response.data;
}, function(error){
//handle error
});
The sort version is
$http.post("/getVotes", { id: $scope.Id }).then(function(response) {
//handle success
$scope.votes_counting = response.data;
}, function(error) {
//handle error
})
Note : You are using a POST method but a GET method seems more appropriate in your case (getVotes)
I've added a snippet, which shows the basic handling of promises. Here, I've used a service to mock a http call. The response is attached to a scope variable, which is presented in the view.
angular.module('TestApp', [])
.factory('MockHttp', function($q) {
return {
getMockData: function() {
return $q.when(['A', 'B', 'C']);
}
};
})
.controller('TestController', function($scope, MockHttp) {
$scope.res = null;
MockHttp.getMockData()
.then(function(res) {
$scope.res = res;
})
.catch(function(err) {
console.log(err);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="TestApp">
<div ng-controller="TestController">
{{res}}
</div>
</div>
The $http function does not return the response of the server. But as you have already figured out you can use the success function to get the servers response. Simply set $scope.votes value in the success function like this:
$http({
method: "post",
url: "/getVotes",
data: { id: $scope.Id}
}).success(function(response){
$scope.votes = response
});
The easiest is probably using $http.post. Note that success is deprecated in favour of then:
$scope.retrieveVotes = function(){
$http.post('/getVotes', {id : $scope.id}).then(function(response){
$scope.votes = response.data;
});
}
Also note that $http calls are asynchronous so calling retrieveVotes is also asynchronous.
I'm trying to build a form in Angular, but i'm new with it, so I need some help :)
I have a field 'email' which should be checked when the user leave that field. A function in my controller should to check the entered value if it already exist in the database (ajax/http).
I found the 'ng-blur' function and have created a function in my controller to check the email. But, the $scope.user.email is undefined, and I don't known what i'm doing wrong. Can somebody help me?
This is my code so far:
HTML (jade)
p.claim-text Email
abbr.required.claim-text(title='required') *
input#billing_email.input-text.form-control.claim-input(type='email', placeholder='Email', value='', name='email', ng-model='user.email', ng-blur='checkEmail()' required)
p(ng-show="registerForm.email.$invalid && !registerForm.email.$pristine").help-block Invalid emailadres
p(ng-show="emailExists").help-block User exists! Click here to login
Controller function
$scope.checkEmail = function(){
console.log($scope.user.email);
$http({
method: 'GET',
url: '[someurl]',
data: $scope.user.email,
}).then(function successCallback(response){
//if response is true, set emailExists to true;
}, function errorCallback(response){
});
}
Please try this snipped
var myApp = angular.module('myApp',[]);
myApp.controller('GreetingController', ['$scope','$http', function($scope, $http) {
//You can check POST at server side to get the entered email
$scope.checkEmail = function(email){
//REMOVE THIS LINE
console.log(email);return false;
$http({
method: 'POST',
url: '[someurl]',
data: email,
}).then(function successCallback(response){
//if response is true, set emailExists to true;
}, function errorCallback(response){
});
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!--HTML -->
<div ng-app="myApp" ng-controller="GreetingController">
<input type="text" ng-blur="checkEmail(email)" ng-model="email"/>
</div>
OR
<!--JADE -->
input#billing_email.input-text.form-control.claim-input(type='email', placeholder='Email', name='email', ng-model='user.email', ng-blur='checkEmail(user.email)' ng-init="user.email=''" required)
You can pass the email to checkEmail function
input#billing_email.input-text.form-control.claim-input(type='email', placeholder='Email', value='', name='email', ng-model='user.email', ng-blur='checkEmail()' required)
Then in controller you just need to get the email from argument
$scope.checkEmail = function(){
console.log($scope.user.email);
$http({
method: 'GET',
url: '[someurl]',
data: $scope.user.email,
}).then(function successCallback(response){
//if response is true, set emailExists to true;
}, function errorCallback(response){
});
}
I am trying to return an object from a $rootScope function called retrieveUser() in AngularJS. The object is returned. I have run console.log() on the response of the function ran when $http is successful. Here is my $rootScope function:
$rootScope.retrieveUser = function() {
var apiUrl = "http://104.251.218.29:8080";
if($cookies.get('tundraSessionString')) {
var cookie = $cookies.get('tundraSessionString');
$http({
method: "POST",
url: apiUrl + "/api/master/v1/auth/checkauth",
data: "sessionString=" + cookie,
headers: {
'Content-Type' : 'application/x-www-form-urlencoded;',
'Cache-Control': 'no-cache'
}
}).then(function mySuccess(response) {
if(response.data.event == "error") {
window.location = "/auth/logout";
} else {
return response.data;
}
})
} else {
window.location = "/auth/login";
}
};
With this method, I access it in my controller such as this (and console.log() just to test my work):
vm.user = $rootScope.retrieveUser();
console.log($rootScope.retrieveUser());
But, I have yet to get this to work. I have tried specifying specific objects in an array in my $rootScope function. I know it runs, because I have the $rootScope consoling something when it is run, and it shows a console.log() of the response of the $http request. It looks like this:
Object {event: "success", table: Object}
event:"success"
table:Object
__proto__:Object
Yet, when I console.log() the vm.user with the function $rootScope.retrieveUser(), even though the function is supposed to be returning the object, I simply receive "undefined".
I have been banging my head on this for days, read some articles on functions/objects and I still cannot figure this out. We're two days in.
try this:
if($cookies.get('tundraSessionString')) {
var cookie = $cookies.get('tundraSessionString');
//return a promise
return $http({
method: "POST",
url: apiUrl + "/api/master/v1/auth/checkauth",
data: "sessionString=" + cookie,
headers: {
'Content-Type' : 'application/x-www-form-urlencoded;',
'Cache-Control': 'no-cache'
}
}).then(function mySuccess(response) {
if(response.data.event == "error") {
window.location = "/auth/logout";
}
else {
return response.data;
}
})
}
else {
window.location = "/auth/login";
}
and
$rootScope.retrieveUser().then(function(user){vm.user = user;})
What you are returning from retrieveUser when your cookie is set is what $http returns, which is a promise. Try this:
$rootScope.retrieveUser().then(function(user){vm.user = user;})
retrieveUser fn doesn't return your data :)
$http is asynchronous function and you should read about promises
function handleUser(user){
//do something
}
function retrieveUser(callback){
$http({...}).then(function(response){
callback(response.data.user);
});
}
//how to use it:
retrieveUser(handleUser);
but first of all you may need a service for getting some data instead of using $rootScope
and secondly you can pass a user in your template in script tag
then you don't need another http request and user will be globaly available
<script>var user=<?php echo json_encode($user);?></script>
I have select tag the options which will come from the service, after adding one more item to scope from the other service i am not getting the newly inserted value in select options, i am able to see the option after refreshing of the page, scope is not fetching the results on changing of its values. here is my code
html code is here
<select ng-model="holidaySelected"
ng-options="opt as opt.holidayName for opt in list_of_holidaytypes">
</select>
js code is here
$http({
method : 'get',
url : 'url'//url is here
}).then(function(response) {
$scope.list_of_holidaytypes = response.data;
});
after another service i am calling this service again but I am not able to see the new option in UI side.
The code is perfect. I feel something fishy with the API response. Can you tell what is the response you are getting from the API. It should be as follows,
$scope.list_of_holidaytypes = [{holidayName:'Name1' }, {holidayName:'Name2' }];
It seems that you are doing $scope.list_of_holidaytypes = response.data; in service while as per angular docs, you can not access $scope inside angular service.
My suggestion is to put the code (which is responsible to fill $scope.list_of_holidaytypes) in the controller.
For example:
Controller Code:
function MyCntrl($scope, MyService) {
function successCallback(response) {
$scope.list_of_holidaytypes = response.data;
}
function failureCallback(response) {
$scope.list_of_holidaytypes = null;
}
$scope.fetchList = function() {
MyService.fetchList(successCallback, failureCallback);
}
}
Service Code:
function Myservice($http) {
this.fetchList = function(successCallback, failureCallback) {
$http({
method : 'get',
url : 'url'//url is here
}).then(function(response) {
successCallback(response);
}, function(response) {
failureCallback(response);
});
}
}
It should work perfectly.
I Found the solution, what I am doing to update the scope variable in UI, I am Calling the service to get the latest scope variable value in side of the service.. here is my code
to update initial state
$scope.OnloadServiceData = function(){
$http({
method : 'get',
url : 'url'//url is here
}).then(function(response) {
$scope.list_of_holidaytypes = response.data;
});
};
$scope.OnloadServiceData();
another controller
$http({
method : 'post',
url : 'url'//this is another service
}).then(function(response) {
$scope.xyz= response.data;
$scope.OnloadServiceData();//calling the service to fetch result in UI
});
try this
before call
var vm= this;
after call user
vm.yourevent;
use
I'm passing the values in angularjs using $http to a url but I'm not able to get the values in AJAX file.
The following is my JS code:
$scope.insert = function() {
var name = $scope.name;
var pass = $scope.password;
alert(name);
alert(pass);
$http({
url : 'http://localhost/anguler/ajax.php?act=abc',
data : {"pass":pass,"name":name},
type : 'POST'
}).success (function(resp){
alert(resp);
});
}
And this is the code in ajax.php:
if(isset($_REQUEST['act']) == 'abc')
{
$user_name=$_POST['name'];
$password=$_POST['pass'];
echo $user_name.'**'.$password;
}
I'm not getting the values for $user_name and $password.
Angular $http has another options, check it out:
$http({
method: 'POST',
url: 'http://localhost/anguler/ajax.php?act=abc',
data: {
"pass": pass,
"name": name
}
})
Not type, but method. https://docs.angularjs.org/api/ng/service/$http#post
Also, you can try to check passing values like
isset($_REQUEST['pass']) == 'pass') { do stuff; }