Unexpected behavior encountered when using the $http.post method

I've been working with a component that I utilized to submit data to the Rest API. The code snippet for the component is as follows:

(function(angular) {
    'use strict';
    angular.module('ComponentRelease', ['ServiceRelease'])
        .component('createRelease', {
            templateUrl: 'components/release/createRelease.html',
            controller: CreateRelease,
            controllerAs: 'clCtrl',
        })

    function CreateRelease($http, getReleaseManagers, insertRelease) {
        var ctrl = this;

        this.$onInit = function() {
            getReleaseManagers.promise($http).then(function(response) {
                ctrl.managers = response.data.releasemanager;
            });

            //the save button
            ctrl.save = function() {
                var release = { "rName": ctrl.r_name, "releaseDate": ctrl.r_date, "releaseSharepoint": ctrl.r_sharepoint, "gManager": ctrl.gname, "pManager": ctrl.pname };

                $http.post('http://localhost:8080/post', release).then(function(response) {
                    console.log("Save in database");
                }, function(e) {
                    console.log(e);

                });
            };
        };
    };
})(window.angular);

When I check the console log after saving, I see "undefined" if it was successful and an error message if there were any errors. Is my understanding correct? If the post was successful, shouldn't I see the message "Save in Database"? I would appreciate your insights on this matter. I am currently using angularjs 1.6

Thank you for your assistance, Eugen

Answer №1

When posting in Angular, make sure to include the header content-type in the configuration so that the server can properly parse the data type (application/json).

(function(angular) {
  'use strict';
  angular.module('ComponentRelease', ['ServiceRelease'])
    .component('createRelease', {
      templateUrl: 'components/release/createRelease.html',
      controller: CreateRelease,
      controllerAs: 'clCtrl',
    })

  function CreateRelease($http, getReleaseManagers, insertRelease) {
    var ctrl = this;

    this.$onInit = function() {
      getReleaseManagers.promise($http).then(function(response) {
        ctrl.managers = response.data.releasemanager;
      });

      //the save button
      ctrl.save = function() {
        var release = {
          "rName": ctrl.r_name,
          "releaseDate": ctrl.r_date,
          "releaseSharepoint": ctrl.r_sharepoint,
          "gManager": ctrl.gname,
          "pManager": ctrl.pname
        };

        var config = {
          headers: {
            'Content-Type': 'application/json'
          }
        }

        $http.post('http://localhost:8080/post', release, config).then(function(response) {
          console.log("Save in database");
        }, function(e) {
          console.log(e);

        });
      };
    };
  };
})(window.angular);

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

An unanticipated SyntaxError was encountered while attempting to utilize an Ajax post, specifically in relation

I can't seem to figure out how to troubleshoot an ajax/jquery error. Here is the function I'm working with: var LogIn = { Email: $("#Name").val(), MobileNo: $("#txtMobileNumber").val(), PinCode: '', ...

What is the best way to access and process data from an $http request in a controller using a service

I am encountering an issue where the return value of the $http service in my controller is coming back as "undefined." Within my controller, I make a call to a service that utilizes $http: //this returns undefined vm.user_instruments = instruments.getIns ...

Combining Various Data Types in a Flexible List

I'm looking for a way to dynamically add rows to a table. Right now, I have the input type on the server (whether it's int, bool, string, etc), but I want to know how to implement a field accept combobox. Here is the code in cshtml: <tr ng-r ...

I am facing an issue where the URL generated in the Controller in Laravel is not functioning properly when

After escaping the single quote, I included a URL link inside the Controller and passed it through json_encode. However, when I clicked on the URL link, it did not work and showed this: The URL appeared like this: http://localhost/BSProject/public/%7B% ...

What is the best method for accessing the properties of a JavaScript object based on input from a textbox?

Just starting out with angular and having trouble generating or updating a table based on text boxes. The schema includes country, sales, and profit fields. There are two text boxes for the x-axis and y-axis inputs. The table should dynamically update when ...

After modifying the select option, the input field remains disabled

I successfully developed a self-contained code snippet that toggles the enable/disable state of input fields. It works flawlessly on my HTML page. Check it out below: Identification Type: <select name="Identification-Type" id="Identification-Type"& ...

Is it possible to use both the filter $select.search and the limitTo $select.infiniteCurrentLimit on a single ui-select field?

I am facing a challenge with my ui-select field which utilizes infinite-scroll functionality due to having a large number of options. However, it becomes cumbersome to scroll down and find the desired option among so many choices. <ui-select-choices ...

Ways to verify the existence of a username in WordPress without the need to refresh the page

How can I check if a username exists in the database without refreshing the page in a Wordpress form using AJAX? I've tried implementing AJAX in Wordpress before but it didn't work. Can someone provide me with a piece of helpful code or a link to ...

Ensure that children elements are aligned to the bottom by setting the axis of the HTML

Elements positioned within a parent DIV typically flow from top to bottom. Even when using Javascript to add elements to the parent DIV, they maintain this top-to-bottom positioning. I am interested in achieving a bottom-to-top axis alignment within the pa ...

Can you explain the sequence of steps involved in setting up a server in node.js?

I'm curious about the order in which instructions are executed in this code. Specifically, I want to know if http.createServer() or server.listen is executed first, and when the callback function inside createserver will execute. const http = require( ...

Several dropdown menus within the same container, working independently of each other

I recently encountered an issue with a drop-down navigation bar. When I have multiple drop-downs and click on one, it opens as expected. However, if I then proceed to click on another drop-down while the first one is already open, both of them remain open ...

The optimal organization of factories in AngularJS

I have a dilemma with my AngularJS single page application where I find myself calling the JSON file twice in each method $http.get('content/calendar.json').success(function(data) {.... Is there a more efficient way to make this call just once, ...

Develop a Vue.js component embedded within another component to manipulate data stored in the parent

After reviewing a few answers that partially address my question, I realized there is more to explain. In our Laravel project website layout, we utilize a global #app div. This means all pages share the same main Vue instance, prompting me to segregate ke ...

What is the best way to enclose a bootstrap row within a clickable link generated by the twitch.tv API?

Recently, I completed a JSON/JavaScript project for Free Code Camp that retrieves streamer information like their logo, current status, and display name. My goal is to enclose entire Bootstrap 3 rows in hyperlinks linked to the streamers' pages, elim ...

Unveiling the Mystery: How Browser Thwarts Server Push in HTTP/2.0

After studying the documentation of HTTP/2.0, I discovered that it is feasible to completely close a referenced stream using the RST_STREAM frame. Check it out here: ()! I am curious about how this feature can be implemented in popular web browsers such a ...

Using Vue to alter data through mutations

Greetings! I am currently in the process of developing a website for storing recipes, but as this is my first project, I am facing a challenge with modifying user input data. My goal is to create a system where each new recipe added by a user generates a u ...

Pass information from ColdFusion to jQuery

I'm attempting to achieve a similar result as this, but I believe the syntax is not quite right: <cfset details = '{ name: "name", address:"address"}' /> <img data-details='#details#' onClick="DisplayDetails()" /> &l ...

Generating a React User-Object in JSON Format

Imagine there is a back-end system using Node.js that allows the creation of users with specific attributes as shown below: POST http://localhost:8080/user Authorization: {{adminToken}} Content-Type: application/json { "userID": "test" ...

a gentle breeze gathers a multitude of entities rather than items

When utilizing a restful server with node.js and sending a collection of entities wrapped in one entity object (Lookups), everything seems to be functioning properly. However, the issue arises when breeze views the entities in the collection as plain objec ...

The jquery live click event is not functioning properly on iPad devices

I am experiencing an issue with a webpage that has the following code to bind click events <script type="text/javascript"> $(".groupLbl").live("click", function(e) { var $target = $(e.currentTarget); ..... $.getJSON("/somelink.js ...