1

Am trying to call Angularjs function outside the controller component like the below :

   <script type="text/javascript">
        function saveprof() {
            $('.spinner').show();
            $.ajax({
                type: "POST",
                url: "saveprof",
                enctype: 'multipart/form-data',
                async: true,
                data: {
                    'rinput_Aj': JSON.stringify(angular.element(document.getElementById('rdExampleApp')).scope().$func()),
                    'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
                },
                success: function (data, textStatus, jqXHR) {
                    $('#message').html(data);
                    window.location.href = 'myprofile';
                    window.location('myprofile');
                    $('.spinner').fadeOut();
                }
            });
        }
</script>

Here is the angularjs controller code :

 <script>
    var app = angular.module('rdExampleApp', ['ui.rdplot']);
    app.controller('rdPlotCtrl', function ($scope) {
        $scope.dataset = {
         "d0": { "id": 0, "name": "Housing", "value": 18 },
         "d1": { "id": 1, "name": "Travel", "value": 31.08 },
         "d2": { "id": 2, "name": "Restaurant", "value": 64 },
         "d3": { "id": 3, "name": "Bank", "value": 3 },
         "d4": { "id": 4, "name": "Movies", "value": 10 }
          };

          $scope.func = function func() {
                 var jdata = $scope.dataset;
                 return jdata;
            }
    });

   </script>

It throws an error Uncaught TypeError: Cannot read property '$func' of undefined

EDIT: After the suggestions, I converted my jquery ajax call to $http function in Angularjs.. But it does nothing.. No error in console :(

Here is how am invoking the $http service function

   <body ng-controller="rdCtrl">
        <a ng-click="saveprof()">Save</a>  

   <script>
    var app = angular.module('rdExampleApp', ['ui.rdplot']);
    app.controller('rdCtrl', function ($scope) {
        $scope.dataset = {
     "d0": { "id": 0, "name": "Housing", "value": 18 },
     "d1": { "id": 1, "name": "Travel", "value": 31.08 },
     "d2": { "id": 2, "name": "Restaurant", "value": 64 },
     "d3": { "id": 3, "name": "Bank", "value": 3 },
     "d4": { "id": 4, "name": "Movies", "value": 10 }
      };

      $scope.func = function func() {
             var jdata = $scope.dataset;
             return jdata;
        }, function ($scope, $http) {
        $scope.saveprof = function () {
            //show spinner        
            $('.spinner').show();
            $http.post('saveprof', {
                data: { 'data': JSON.stringify($scope.dataset) }
            })
                      .success(function (data) {
                          if (data == "null") {
                              //your code if return data empty 
                          } else {
                              //your code if return data not empty 
                              $('#message').html(data);
                          }
                          //hide spinner
                          $('.spinner').fadeOut();
                      })
                      .error(function (data, status, headers, config) {
                          console.log('error' + status);
                          //hide spinner in case of error
                          $('.spinner').fadeOut();
                      })
        }
    }
    );
</script>
</body>

What am I missing?

7
  • Why are you using jQuery's AJAX instead of Angulars? Commented Nov 30, 2015 at 17:24
  • Am not familiar with Angularjs Ajax call, how it does work.. Commented Nov 30, 2015 at 17:24
  • if you must do it that way for what ever reason just do var scope = 'angular.element($('#someelement')[0]).scope(); scope.<whatever functionname>(); scope.$apply();. but unless you have a really good reason like external services and stuff like that you should always use $http or $resource for AJAX comms Commented Nov 30, 2015 at 17:26
  • @SathishPanduga -- Read the Angular docs for the $http service - DONT mix and match jQuery and Angular like this - it'll cause more problems than it solves. Commented Nov 30, 2015 at 17:28
  • @DayanMorenoLeon Thanks a lot for suggesting it.. If I use $http for ajax call, can I do exactly the same as my jquery ajax call in angular js ajax call? Could you pls give similar model in Angularjs ? Commented Nov 30, 2015 at 17:46

1 Answer 1

4

in order to run XMLHttpRequest requests to the server you have many options in angularjs, you dont have to mess with simple javascript and call angular scope to get variables and functions. you can do that either with $http or with services(leave it for now).

i am going to show how you can make the request with $http in native angular.

  1. first of all you have to import the $http module on the declaration of your controller, like this :

    var app = angular.module('rdExampleApp', ['ui.rdplot']);
    app.controller('rdPlotCtrl', function ($scope,$http) {...});
    
  2. into you controller you create the json object as you do it and then do the request like this:

      //show spinner        
     $('.spinner').show();        
     $http.post('dal/addEventHalls.php', {
         data: {'data': $scope.datase}
           })
               .success(function (data) {
                  if (data == "null") {
                     //your code if return data empty 
                  } else {
                      //your code if return data not empty 
                  }
                  //hide spinner
                  $('.spinner').fadeOut();
              })
               .error(function (data, status, headers, config) {
                  console.log('error' + status);
                   //hide spinner in case of error
                  $('.spinner').fadeOut();
               })
    
  3. as you can see we dont use url parameter but we pass the url directly into post() function. the data parameter is there to put whatever data you would like to send to the server.

hope helps good luck.

UPDATE

  1. personally i dont stringify the data parameters.i pass them like json object
  2. into php file , in order to get the data , try this:

    $params = json_decode(file_get_contents('php://input'), true); //read values from angular factory-service

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot for simple example! Just a question, how can I pass multiple variables in data ? like I have some other input text field value $('#name').val().. is it like data: {'data' : $scope.dataset, $('#name').val()} ? also, can I post the data as json format directly ?
dont forget that you pass an object so you need a key value pair: data : {'name':$scope.name, 'lastname': $('#name').val(), etc. }
Hi Theo, I converted ajax call as you suggested, but it does nothing when I try to invoke the call via ng-click.. Could you pls check my updated question ?
hello, first of all i dont see the $http on your controller declaration. you should get error like this if you dont add it: ReferenceError: $http is not defined. have you checked the console messages of your browser ? if you dont get any errors, this means that your code gets into success function. right? 1. into post use the path of your php file just to be sure 2. please just pass your json object and dont stringify it 3. into your php file get the data like this: $params = json_decode(file_get_contents('php://input'), true);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.