Guide on how to execute an AngularJS controller function externally during an AJAX request

I am attempting to invoke an Angularjs function outside the controller component as shown 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>

Below 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>

An error is thrown stating: Uncaught TypeError: Cannot read property '$func' of undefined

UPDATE: Following recommendations, I replaced my jQuery ajax call with the $http function in Angularjs, however, it does not work and no errors are displayed in the console.

Here's how I am calling 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, $http) {
        $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;
        }

        $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>

Any insights on what could be missing?

Answer №1

When it comes to making XMLHttpRequest requests to the server in AngularJS, there are multiple options available that eliminate the need to rely on plain JavaScript and accessing Angular scope for variables and functions. You can achieve this functionality using either $http or services (we will discuss this later).

Let's explore how you can make a request using $http within native Angular.

  1. To begin, you must import the $http module when declaring your controller, like so:

    var app = angular.module('rdExampleApp', ['ui.rdplot']);
    app.controller('rdPlotCtrl', function ($scope,$http) {...});
    
  2. Within your controller, create a JSON object as needed and make the request in the following manner:

    // Show spinner
    $('.spinner').show();        
    $http.post('dal/addEventHalls.php', {
    data: {'data': $scope.datase}
    })
    .success(function (data) {
    if (data == "null") {
    // Your code if returned data is empty 
    } else {
    // Your code if returned data is not empty 
    }
    // Hide spinner
    $('.spinner').fadeOut();
    })
    .error(function (data, status, headers, config) {
    console.log('error' + status);
    // Hide spinner in case of an error
    $('.spinner').fadeOut();
    })
    
  3. Notice that we don't use the url parameter but instead directly pass the url into the post() function. The data parameter allows you to include any data you wish to send to the server.

I hope this helps. Good luck!

UPDATE

  1. I personally do not stringify the data parameters but pass them as a JSON object.
  2. In the PHP file, to retrieve the data, try the following:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to send e.target data back to the server?

Currently, I have a front-end system in place to monitor which element has been clicked and send that information back to the server for further processing. The implementation is as follows: $('body').on('click', function(e) { $.po ...

Encountering 'error: undefined' message in dropzone.js success function

I created an Angular.js directive that adds a dropzone to my app and binds a function to the success event of dropzone.js. However, I am only able to retrieve the response and the file is undefined. The response is coming from the API that uploads the file ...

Finding the weekdays that occur within the past week using JavaScript

I have an array of timestamps and I want to extract only the weekdays from the timestamps that fall within the last seven days. Currently, my code retrieves all Saturdays from the timestamps, but I need it to filter out only the relevant weekdays within a ...

Retrieve user-specific relational data

In my Supabase database, I have three main tables: users, teams, and members. The users table stores information about all users who sign up using auth. Here are the details contained in this table: id displayname email 602eff1e-6300-491e-b821-44e ...

I am experiencing issues with the functionality of my ajax form request

I am trying to display an alert message on my page but it doesn't seem to be working. Below is the code from my view: $.ajax({ url :"<?php echo base_url();? >booking/dispatch_challan/DispatchChallanController/createDispatchChallan", ...

Encountering a SyntaxError while implementing lightweight-charts in NextJS

I'm encountering an issue while trying to integrate the lightweight-charts package into my nextjs project. When attempting to utilize the createChart function, I am receiving a syntax error in my Node.js console. ...\lightweight-charts\dist& ...

Generate a table in MongoDB using NestJs without the need to create a new collection

I am facing a challenge with my app where I need to create an order with multiple attributes, one of which is an array of ordered products. Each object in the orderedProduct array must include the productId and the amount. However, I do not want to create ...

Trouble getting Fontawesome icons to accept color props when using react functional components with tailwindcss

Issue I'm Facing I'm currently working on a project that involves using icons extensively. Instead of manually adding a Fontawesome icon in every script, I have created a functional component that handles the rendering of icons based on given pr ...

Tips on obtaining a variable passed via the GET method using AJAX

Can someone assist me with using AJAX? I have a code that loads a .php file with additional data. How can I utilize this data to load a new page? Below is the code snippet: function cancelRecommendation(idData) { $.get("cancel_recommendation.php", { ...

Looking to retrieve data using Cheerio? If you're finding that the data appears empty in the page source but is visible when inspecting the elements, here's how you can go

I am encountering difficulties while trying to scrape data from another website. In my case, I notice that the data appears empty when viewing the page source, but it is visible when inspecting the elements. If you're confused, please refer to the fol ...

Ways to detect when modifier keys are pressed during a click event on a deck.gl layer

When working with deck.gl's IconLayer, I want to be able to listen for shift-clicks on icons. The goal is to enable multiple icon selections by holding down the shift key. My setup involves using deck.gl in conjunction with Google Maps. Upon clicking ...

Split the string into individual parts and enclose each part in HTML using JavaScript

Currently, I am utilizing a content editable div to create tags. Upon pressing the return key, my objective is to select the preceding text (excluding the prior tags) and transform it into a new tag. The format for a tag will be enclosed within . For insta ...

JavaScript encounters an unexpected identifier: Syntax Error

I encountered a syntax error while executing the code below: var userAnswer = prompt("Do you want to race Bieber on stage?") if userAnswer = ("yes") { console.log("You and Bieber start racing. It's neck and neck! You win by a shoelace!") } else { ...

Is there a way to prevent users from right clicking on all links with the same class using js/jquery?

Rails 4 + JS + jquery Is there a way to disable right click on links with the same class in Rails? <% @schedule_hash.values.each do |schedule| %> <%= link_to "Cancellation policy", {:controller => 'web', :action => 'get ...

Retrieve various URLs within an object using React

My task involves extracting all URLs from a specific object. Object { "Info": "/api/2", "Logo": "/api/2/Logo", "Photo": "/api/2/photo", } I aim to store the responses in a state, ensuring t ...

The AngularJS error message: TypeError: Unable to access the 'images' property because it is undefined

Currently using AngularJS version 1.5.11 I am attempting to present images sourced from a JSON array. Is my method correct: $scope.mainImage = $scope.template.images[0].name;. The issue arises at the line where it says it cannot read property of images. ...

What's the best way to abbreviate my code as "print(//some text)?

Currently delving into the world of JavaScript, I have been working on a code that involves continually displaying new alerts on the screen. To achieve this, I managed to find a way to directly print these messages on the screen, which is functioning flawl ...

Retrieve a reaction from the node.js server and trigger a separate function if a specific condition is met

Running a small node.js server with basic routes, I'm using ajax to fetch data from the server on an index.html page. Upon opening the website, the user's login status is checked. If not logged in, the user gets redirected to /login route. Once ...

Experiment with using jasmine to test angularJS components within a rails application

Having some trouble setting up unit tests for my AngularJS app. Jasmine doesn't seem to recognize the controller, even though it's registered in the global namespace: ReferenceError: RequestsController is not defined. Check out this gem for more ...

Is it advisable to specify data types for my JSON data in TypeScript?

For the shopping application in my project, I am utilizing a JSON structure to categorize products as either hot or branded. However, I encountered an issue when trying to define a type for the entire JSON object labeled "full". Despite my attempts, it app ...