Troubleshooting: AngularJS Http Post Method Failing to Execute

I am attempting to make an HTTP POST request to update my database using AngularJS. Although my code is not displaying any errors, the database is not being updated and I'm having trouble pinpointing the issue. Below is the code snippet:

//topic-service.js

  (function() {
        'use strict';
        angular.module('topic').factory('topicService', topicServiceFunction);
        topicServiceFunction.$inject = [ '$http', '$q' ];
        function topicServiceFunction($http, $q) {
            var topicService = {
                getTopics : getTopics

            }
            return topicService;

            function getTopics(obj) {
                console.log('-->topicServiceFunction');
                console.log(obj.name);
                var deferred = $q.defer();
                return $http.post('http://localhost:8080/restapp/api/topic',
                        JSON.stringify(obj)).then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        return deferred.reject(response.data);
                    }
                }, function(response) {
                    return deferred.reject(response.data);
                });

            }

        }

    }())

//topic-controller.js

 (function() {
        'use strict';
        angular.module('topic').controller('topicController',
                topicControllerFunction);
        topicControllerFunction.$inject = [ '$scope', 'topicService' ];
        function topicControllerFunction($scope, topicService) {
            $scope.getTopics = getTopics;
            function getTopics(topicId,name,description,categId,userId) {
                 console.log('-->topictrlFunction');
                $scope.topics = [];

                var obj={
        id:$scope.topicId,
        name:$scope.name,
        description:$scope.description,
        id_category:$scope.categId,
        user_id:$scope.userId

        }
        var promise = topicService.getTopics(obj);
                promise.then(function(data) {
                    if (data != undefined && data != null) {
                        $scope.topics = data;
                    } else {
                        $scope.topics = undefined;
                    }
                }, function(error) {
                    console.log('error=' + error);
                    $scope.topics = undefined;
                })
                topicService.getTopics(obj);
                $scope.topics = topicService.getTopics(obj);
            }

        }
    }())

//topic.html

 <!DOCTYPE html>
    <html lang="en" ng-app="myTopics">
    <head>
    <meta charset="UTF-8">
    <script src="../../../bower_components/angular/angular.js"></script>
    <script src="app.js"></script>
    <script src="topics/module/topic-module.js"></script>
    <script src="topics/controller/topic-controller.js"></script>
    <script src="topics/service/topic-service.js"></script>
    <title>Topics</title>
    </head>
    <body>

        <div ng-controller="topicController">
            <div ng-controller="topicController">
                <p>
                    Topic id: <input type="text" ng-model="topicId">
                </p>
                <p>
                    Name: <input type="text" ng-model="name">
                </p>
                <p>
                    Description: <input type="text" ng-model="description">
                </p>
                <p>
                    Id category: <input type="text" ng-model="categId">
                </p>
                <p>
                    User id: <input type="text" ng-model="userId">
                </p>
                <button ng-click="getTopics(topicId,name,description,categId,userId)">Add
                    topic</button>
                <ul ng-repeat="topic in topics">
                    <li>{{topic.id}} --{{topic.name}} -- {{topic.description}} --
                        {{topic.id_category}}--{{topic.user_id}}</li>
                </ul>

            </div>
    </body>
    </html>

Answer №1

When working on your service, try to avoid using $q and returning $http promise as it can be counterproductive. Instead, consider returning a deferred promise like this:

function getTopics(obj) {

      console.log('-->topicServiceFunction');
      console.log(obj.name);

      var deferred = $q.defer();
      var data = JSON.stringify(obj)

      $http.post('http://localhost:8080/restapp/api/topic', data)
          .then(function(response) {
              if (typeof response.data === 'object') {
                  deferred.resolve(response.data);
              } else {
                  deferred.reject(response.data);
              }
           })
           .catch(function(response) {
              return deferred.reject(response.data);
           });

    return deferred.promise;

 }

If you're still encountering issues, consider sending urlencoded data instead of json:

To do this, simply include the following header in your request:

headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}

Make sure to encode the data using the $httpParamSerializerJQLike service. Don't forget to inject it into your service.

function getTopics(obj) {

      console.log('-->topicServiceFunction');
      console.log(obj.name);

      var deferred = $q.defer();
      var data = $httpParamSerializerJQLike(obj);
      var config = {
         headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
      };

      $http.post('http://localhost:8080/restapp/api/topic', data, config)
          .then(function(response) {
              if (typeof response.data === 'object') {
                  deferred.resolve(response.data);
              } else {
                  deferred.reject(response.data);
              }
           })
           .catch(function(response) {
              return deferred.reject(response.data);
           });

    return deferred.promise;

 }

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 advantages does event delegation in JavaScript offer compared to using jQuery's event handling?

Vanilla JavaScript: parentNode.addEventListener("click", function(event) { if (event.target === childNode) { code here } }); versus jQuery: $(parentNode).on("click", childNode, function() {}); ...

Transferring PHP and JavaScript variables via AJAX to PHP page and storing in MySQL database table

After searching through numerous similar questions, I still haven't found the exact answer I need. I have a set of js variables that are sent via ajax to a location.php file, where they will be inserted into a mysql table. The current ajax call looks ...

When trying to post in Express, the object named "<Object>" is not able to find the "validate" method

I am currently working on developing a poll application using Angular and Express. The majority of the project is complete, but I am facing an issue with the app crashing when attempting to POST data. In the express console, the only error message I'm ...

"Utilizing Angular's built-in functionality to enable drag-and-drop behavior on an element within

Currently, I am working with Angular and JSPlumb. My goal is to bind the draggable behavior from jsplumb to my element in the directive by using the element in the link function. This is how I currently approach it (http://jsfiddle.net/r8epahbt/): // In ...

Retrieve the attributes associated with a feature layer to display in a Pop-up Template using ArcGIS Javascript

Is there a way to retrieve all attributes (fields) from a feature layer for a PopupTemplate without explicitly listing them in the fieldInfos object when coding in Angular? .ts const template = { title: "{NAME} in {COUNTY}", cont ...

Choose particular ng-repeat elements to emphasize them in a different location

I am currently working with a list that is being parsed by an ng-repeat directive. The user has the ability to filter this list, which is functioning correctly. One particular feature I am trying to implement is highlighting the first item in the filtered ...

The necessary directive controller is missing from the element in the current DOM structure

Can anyone explain the meaning of "required directive controller is not present on the current DOM element"? I encountered this error and would like some clarity. For reference, here is the link to the error: https://docs.angularjs.org/error/$compile/ctr ...

Delete the class when the user clicks anywhere on the page

I have 2 buttons that will toggle/remove a class when the user clicks on them. $('.social-toggle').on('click', function() { $('.social-networks').not($(this).next()).removeClass('open-menu') $(this).next().toggl ...

Unnecessary Page Diversion

Within my index.php file, I have a download button with the id of "render". Using AJAX, I am sending a request to the server. The JavaScript code being utilized is as follows: $('#render').click(function(e){ $('html,body').animat ...

navigation bar: retain link hover state even after displaying sub-menu

My navigation bar has submenus with background images in .png format. Only 3 links in my navbar have these submenus. The issue I am facing is that when the menu link is in a hover state and the submenu is being hovered over, the nav link loses its hover st ...

Creating dynamic DIV elements in an AngularJS file using data retrieved from a Sql server

I need to dynamically add elements based on data retrieved from a MSSQL server in the specified area: <div id="ApplicationForm" class="tabcontent" style="display:none;"> <div class="tab_section"> ...

The folder serves as a module, however, the index.js file within the folder only consists of a few require

Currently, I am delving into the source code of hexo, a project built on top of node.js. Specifically, I came across a file named init.js: if (results.config){ require('./plugins/tag'); require('./plugins/deployer'); require('./pl ...

Enhance a Javascript object by dynamically introducing new elements

I am currently working on a webpage using HTML and jQuery. My goal is to create a form where users can enter an email address in a textbox, and when they click a button, the email should be added to an object that displays all the emails entered so far. Th ...

Redux - The same reducers, containers, and components are yielding varying outcomes

update: Issue resolved by connecting a different variable to the mapStateToProps. I'm encountering some challenges with my react-redux application and I'm struggling to pinpoint the error in my setup. You can access the source code here. The f ...

What causes variations in running identical code between the Node environment and the Chrome console?

let myName = "World"; function functionA() { let myName = "FunctionA"; return function() { console.log(this.myName); } } functionA()(); Executing the code above in my terminal with node results in undefined, while running it in Chrom ...

Deciphering JavaScript script within a Node.js module

// =============================================================================== // Auth // =============================================================================== const admin = require('firebase-admin'); //what happens if i move th ...

What is the best way to attach a Label to a THREE.Mesh object?

I'm looking to show the name of a Three.js Three.Mesh as a label when hovering over the mesh. Does anyone know how to achieve this in Three.js? Could someone provide an example code snippet for this? ...

Is it better to have JavaScript and HTML in separate files or combined into a single HTML file?

Do you notice any difference when coding in both HTML and JavaScript within a single .html file compared to separating HTML code in a .html file and JavaScript code in a .js file? Does the functionality remain the same in both scenarios? For example, in t ...

Developing custom validation with Angular 1.5 based on external data inputs

Is it possible to create a custom validation directive in Angular 1.5 that takes into account values other than the bounded one? For example: I have an array of objects of type Type1 with fields Field1, Field2, and Field3. Using ng-repeat, I display the ...

Mongoose: execute population step after making the query

What is the proper way to populate the query result in Mongoose after executing a query similar to this: users .find({name:"doejohn"}) .skip(3) .limit(9) .exec((err,user) => { user // result ...