AngularJS POST request not functioning as expected

Seeking guidance in my AngularJS journey as a newcomer. I'm facing an issue where the call to the REST service is not reaching it despite including everything from controller and service to the actual service call.

Here's a snippet of my code:

app.config(function ($routeProvider) {
   $routeProvider       
    .when('/addNewNote', {
     controller: 'AddNewNoteController',
     templateUrl:'views/addNote.html'
     })

The AngularJS controller implementation looks like this:

app.controller('AddNewNoteController', ['$scope','savenote', function($scope,savenote) {

    savenote.success(function(eData){
            $scope.msg = eData;   

This is the Angular service used for calling the HTTP POST REST service:

app.factory('savenote',['$http',function($scope,$http){

    return $http({
        method: 'POST',
        url: <url is pasted here>,
        dataType: 'json',
        data: {
        "title" : "123dddd",
        "contents" : "123ddddtttttt"
    },
        headers: { 'Content-Type': 'application/json; charset=UTF-8' }
    })          

 }]);

And lastly, here's the snippet for the REST service itself:

@Path("/savenote")
@POST
@Consumes(MediaType.APPLICATION_JSON)  
@Produces(MediaType.APPLICATION_JSON)  
public UserMessages saveNewNote(Note note) throws IOException {       
   .....
}

Answer №1

Don't forget to include the type hint for $scope:

app.factory('savenote',['$scope', '$http', function($scope,$http){

In addition, ensure that your factory returns an object with specific methods:

app.factory('savenote', ['$scope', '$http', function ($scope, $http) {
    return {
        save: function () {
            return $http({
                method: 'POST',
                url: "<url is pasted here>",
                dataType: 'json',
                data: {
                    "title": "123dddd",
                    "contents": "123ddddtttttt"
                },
                headers: {'Content-Type': 'application/json; charset=UTF-8'}
            });
        }
    };
}]);

Remember to use it in this manner:

savenote.send().then(function(eData) {});

Furthermore, as pointed out by @SarjanDesai in a comment, remove the unused $scope from your factory.

Answer №2

savenote function returns an $http object that includes a then function for handling success and failure callbacks.

To update your controller function, use the following code snippet:

savenote.then(function successCallback(eData) {
    $scope.msg = eData;   
}

The legacy promise methods success and error within $http have been deprecated. It is recommended to utilize the standard then method instead. If you set $httpProvider.useLegacyPromiseExtensions to false, these methods will throw a $http/legacy error.

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

The JQUERY Uncaught Error: Syntax error message popped up when trying to access an unrecognized expression on the javascript: void(0)

I've encountered an issue after upgrading to jQuery 3.4.1 while using bootstrap 3. The console keeps showing this error: Uncaught Error: Syntax error, unrecognized expression: # Here is the section of code causing the error: <div class="btn-grou ...

JavaScript - Image style alterations are not operating as expected

Let me break it down for you: onmouseover="imageOn(bg-index);" onmouseout="imageOff(bg-index);" I've got these two attributes set on a table tagged with ID table-title. These functions are included in an external JS file: If the name is 'bg-i ...

Adding data to the second table using Objective C

I am facing an issue with my tableView implementation. I have two tables (Cell Identifier: Call and Cell Identifier: Cell2) and I'm passing two arrays of Objects, one for each table. However, when I try to display the data in my tableView, the second ...

Update all items in the menu to be active, rather than only the chosen one

Here is the layout of my menu along with the jQuery code included below. The functionality is such that when I click on Home Page, its parent element (list item) receives an active class. Currently, when I am on the Home Page, the list item for Account Co ...

The issue at hand is the malfunctioning of Angular form submission within an ng-repeat loop

Whenever I submit a form within an ng repeat loop, the form value does not get passed. <li ng-repeat="com in post.comments">{{ com.body }} <h4>Reply</h4> <form ng-submit="addReply()"> <textarea n ...

Vue.js SyntaxError: Identifier came out of nowhere

An error was reported by VUE debug mode in this line of my code: :style="{transform : 'translate3d(' + translateX + 'px,0, 0)'}"\ The documentation does not provide instructions on how to include a variable within a style binding ...

Ways to align images of the same size in a gallery using the margin: auto property

I have an image gallery within a div element named "container" with a specified width:70%. I need the images to be justified with auto margins. This is the HTML code I am using: (There are 4 images in total) <div class="container"> < ...

Create a duplicate of a div element, including all of its nested elements and associated events, using

Attempting to duplicate a div containing input fields but the event listeners are not functioning. Despite performing a deep copy in the following manner - let rows = document.querySelectorAll('.row'); let dupNode = rows[0].cloneNode(true); sh ...

How to efficiently pass props between components in NextJs

This is the project's file structure: components ├─homepage │ ├─index.jsx ├─location │ ├─index.jsx pages │ ├─location │ │ ├─[id].jsx │ ├─presentation │ │ ├─[id].jsx │ ├─_app.jsx │ ├─index.jsx ...

Developing a void or vacancy using three.js

Thinking about creating a unique shape in three.js, similar to a 3x3x3 cube with a 1x1x1 hole in it. Is there a way to use cubegeometry initially and then apply another geometry to remove the unwanted parts, like a deletion geometry? :D Appreciate any hel ...

Observing modifications in the $route object - Vue Router

I am currently working on a small CRM project. Within the login form, I have implemented a component that displays an alert message when the email or password entered is incorrect. Interestingly, even after correcting the information and logging out, the m ...

Moving the query function from routes to the repository in Laravel

Greetings! I am relatively new to the world of Laravel and I am in the process of setting up a repository to consolidate repeated database calls. It seemed logical to centralize these calls for easier reference. Currently, I have a chained select feature t ...

How to enhance a class in JavaScript by adding a dynamic property

Within my code, I've defined a class which looks like this: class classA { id: number; name: string; constructor(data){ this.id = data?.id || 0; this.name = data?.name || ''; } } What I aim to do now is add ...

json4s - inability to parse a basic string value

Why does the encoding work for "bla-b" but the parsing does not? scala> import org.json4s._ import org.json4s._ scala> import org.json4s.native.JsonMethods._ import org.json4s.native.JsonMethods._ scala> import org.json4s.JsonDSL._ import org.j ...

Authorization error: The specified URL is not permitted by the application settings for Facebook login using the Javascript SDK

Encountered an error while trying to implement Facebook login using Javascript SDK in Chrome console: The given URL is not permitted by the application configuration: One or more of the URLs provided are not allowed by the app's settings. It must ...

Transform intricate JSON data into a structured dictionary format

Hello, I have a JSON file that I am able to modify, but I need to access it by its name. I need to access it in this way: var result = sitelang.brands["en"]; // or var result = sitelang.["brands"]["en"]; Did I make it understandable? I am not a nati ...

What is the reason behind JSLint's preference for x === "undefined" over typeof x == "undefined"?

I'm feeling lost when it comes to JSLint. Initially, my code checked if div:jqmData("me") was undefined in this way: if ( typeof el.jqmData("me") == "undefined" ? el.not(':jqmData(panel="main")').length > 0 : el.not(':jqm ...

Modify session variable upon link click

Here is an extension of the question posed on Stack Overflow regarding creating a new page for different PHP ORDER BY statements: Create a new page for different php ORDER BY statement? The task at hand requires changing a session variable and refreshing ...

Search for an element deep within a tree structure, and once found, retrieve the object along with the specific path leading to

I created a recursive function to search for a specific object and its path within a tree structure. However, when I changed the target ID (from 7 to 10) in the function, I encountered an error: "message": "Uncaught TypeError: Cannot read ...

What is the best way to send AJAX post data to a Node.js server?

I am currently facing an issue with passing a unique ID object back to the server side using Ajax after making an API call. I need help figuring out what might be going wrong in my code. This is the client side code snippet where I loop through a JavaScri ...