0

I am trying to get the first name of the user in the ajax method and trying to print it on the html page but it is not getting printed

this is my html:

<div ng-app="app" ng-controller="VolController">
<div class="account-action">

<h3 style="display:inline;"><img class="img"  align="left" src="images/u11.png">
    <p style="color:white">&nbsp;&nbsp; Welcome {{first_name}}<p></h3>  
</div>

this is my controller:

    app.controller('VolController',['$scope','$sessionStorage','$state',function($scope,$sessionStorage,$state){

    var b=sessionStorage.getItem("userid"); 

    var a="http://localhost:8080/volunteers/"+b;


        $.ajax({
    type:'GET',
    url:a,

    success:function(data){
     console.log(JSON.stringify(data));
    $scope.volunteer=data; 
    $scope.first_name=JSON.stringify($scope.volunteer.VolunteersDTO.first_name);

    console.log(data);


    },
    error:function(data){
        alert(data);
        },
    dataType:"json",
    contentType:"application/json",
})




}]);

Question Updated!!!!

Urkilashi
  • 35
  • 1
  • 4
  • `$scope` is missing, `first_name` should be defined as scope variable in controller. Like: `$scope.first_name=JSON.stringify($scope.volunteer.VolunteersDTO.first_name);` – Sachet Gupta Apr 03 '17 at 06:32
  • tried it.. plese see the qstn once again.. its still not working – Urkilashi Apr 03 '17 at 06:39
  • You are working with Javascript AJAX, you have to let angular know that something has changed or a Scope variable has been updated outside the context of Angular. For this, use `$scope.$apply`. Check this: http://stackoverflow.com/a/21128340/4221611 – Sachet Gupta Apr 03 '17 at 06:45

3 Answers3

0

You should use $scope,

  $scope.first_name=JSON.stringify($scope.volunteer.VolunteersDTO.first_name);
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

As you use $.ajax instead of native $http, you should wrap assigning into $apply:

success: function(data) {
    $scope.$apply(function(){
        $scope.volunteer = data;
        $scope.first_name = JSON.stringify($scope.volunteer.VolunteersDTO.first_name);
    });
}
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26
  • Thanks for the help.Do we have to call that function or will it get called as the page loads. plus,where do we have to include it in the controller? – Urkilashi Apr 03 '17 at 06:34
  • You should use it whenever you call not angular async stuff: like `$.ajax` instead of `$http` or `setInterval` instead of `$interval`. – Slava Utesinov Apr 03 '17 at 06:38
0

Don't make ajax call using jquery $.ajax. Please make ajax call using $http service of angularjs.

$http.get(url);

Do not forget adding $http service as dependedency in angular.

kaushlendras
  • 220
  • 1
  • 7