An issue arose when attempting to submit data from an AngularJS form

I am having an issue with my AngularJS form that is supposed to post data to a Scalatra servlet. Unfortunately, when the form is submitted, I am unable to retrieve any form parameters in my Scalatra servlet.

Here is a snippet of my code:

AngularJS

$scope.createUser = function() {
    $http.post('/createUser',{name:$scope.name,email:$scope.email,pwd:$scope.pwd}).
        success(function(data, status, headers, config) {
            alert("success " + data)
        }).
        error(function(data, status, headers, config) {
            alert("failure =>" +data)
        });
 };         });
 };     

HTML form

<form ng-controller="UserController">
            <legend>Create User</legend>

            <label>Name</label>
            <input type="text" id="name" name="name" ng-model="name" placeholder="User Name">

            <label>Email</label>
            <input type="text" id="email" name="email" 
                ng-model="email" placeholder="ur email here">

            <label>Password</label>
            <input type="text" id="pwd" name="pwd" 
                ng-model="pwd" placeholder="ur own pwd here">

            <button ng-click="createUser()" class="btn btn-primary">Register</button>
        </form>

Scalatra Servlet

post("/createUser") {
    println(params("name")) 
}

Upon submitting the form, I encounter the following error:

Error 500 key not found: name (obtained from firebug lite)

If anyone knows what mistake I might be making or if there is another approach I should consider, please do let me know.

Answer №1

Make these two adjustments for better functionality:

  1. Implement the 'ng-submit' event handler.
  2. Encapsulate the ng-models within an object to simplify data submission.

Here is how you can modify your HTML and JS code:

<div ng-controller="UserController">
  <form ng-submit="createUser()">
    <input type="text" ng-model="user.name">
    ...
    <input type="email" ng-model="user.email">
    ...
  </form>
</div>

Adjust your JavaScript controller as follows:

function UserController($scope, $http) {
  $scope.user = {};
  $scope.createUser = function() {
    $http.post('/createUser', $scope.user);
  }
}

Answer №2

My solution to this problem was to include header information in the http post request itself. Here is the code snippet:

$scope.createUser = function() {
$http({
method: 'POST',
url: '/createUser',
data: 'name=' + $scope.user.name + '&email=' +$scope.user.email,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

}

If you have any suggestions for an alternative approach, feel free to share them.

Answer №3

I encountered a similar issue where the data was not being received in the POST method using $_POST or $_REQUEST.

Fortunately, I found a solution that worked for me:

$data = json_decode(file_get_contents("php://input"));

Answer №4

I apologize for the delay in responding, but I believe my answer may still be of use to someone else.

If you need to access the body of a request submitted as POST, you can retrieve it using the reader of HttpRequest like this:

      BufferedReader reader = request.getReader();
      String line = null;
      while ((line = reader.readLine()) != null)
      {
        sb.append(line);
      }

 String requestBody = sb.toString();

I hope this information proves helpful.

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

Video player on website experiencing issues with playing VAST ads

Hey there! Check out this awesome site for Music Videos: (Music Videos(Player)) I've been testing different options, but if you have a better suggestion, please let me know. Any help would be really appreciated. If I can't figure it out on my o ...

Navigating Express HTTP Requests within Apollo Link Context in a NextJS Web Application

Currently, I am in the process of developing a NextJS application and facing a challenge with accessing a cookie to utilize it for setting a Http Header within a GraphQL Request. For this task, I am integrating apollo-link-context. Below is the snippet of ...

What changes can be made to the HTML structure to ensure that two form tags function separately?

Hey there! I'm currently tackling a web project that involves incorporating two form tags on one page, each with its own distinct purpose. Nevertheless, it appears that the inner form tag isn't behaving as it should. My suspicion is that this iss ...

The express response fails to include the HTML attribute value when adding to the href attribute of an

When using my Nodejs script to send an express response, I encounter a problem. Even though I set the href values of anchor tags in the HTML response, they are not visible on the client side. However, I can see them in the innerHTML of the tag. The issue ...

Is there a way to update the value of a variable with the help of a checkbox?

When I check the checkbox, the specOrder const gets updated as expected. However, I am struggling to figure out how to remove the value when the checkbox is unchecked. Below is the code I have been working on: const SpecialtyBurgers = () => { cons ...

The requested page for angular-in-memory-web-api could not be located within the Angular 4.2.2 CLI web-api functionality

Currently, I am delving into the Angular framework (specifically version 4.2.2) and going through the Tour of Heroes tutorial. As I progressed to the HTTP section, the tutorial introduced the use of angular-in-memory-web-api to simulate a web api server. ...

Husky and lint-staged failing to run on Windows due to 'command not found' error

I'm facing issues with getting husky and lint-staged to function properly on my Windows 10 system. Here's how my setup looks like: .huskyrc.json { "hooks": { "pre-commit": "lint-staged" } } .lintstagedrc ( ...

Incorporating fresh components and newly defined attributes in Angular

Is there a way for me to click on a new component button, specify a name, description, select type, and add attributes such as default value and type? I need all this information to be saved and for the new button to appear in the drag-and-drop section. ...

Using multiple selectors in JQuery and Javascript

I have a challenge where I need to execute different actions for specific divs. Here is the code snippet I currently have: $("#pending-cancel-1, #pending-cancel-2").click(function(){ Do something special for pending-cancel-1 and pending-cancel-2... }) ...

"What is the best way to ensure that a random array value is printed accurately within an If/Else statement in my Text Adventure

I am currently developing a text-based adventure game where the output in the console log is determined by specific input. The goal is for a message to appear if a goblin inflicts enough attack damage to reduce the player's defense to below 0, stating ...

Replicating a tag and inputting the field content

Scenario: An issue arises with copying a label text and input field as one unit, instead of just the text. Solution Needed: Develop a method to copy both the text and the input field simultaneously by selecting the entire line. Challenge Encountered: Pre ...

Easy steps to dynamically add buttons to a div

I need help with a JavaScript problem. I have an array of text that generates buttons and I want to add these generated buttons to a specific div element instead of the body. <script> //let list = ["A","B","C"]; let list = JSON.p ...

Converting Node.js Date.toString() output into a time format in Go

My go service is currently receiving data from an external source. Here's how the data appears (in JSON format)- { "firstName": "XYZ", "lastName": "ABC", "createdAtTimestamp": "Mon Nov 21 2 ...

What is the proper way to utilize useRef with HTMLInputElements?

Dealing with React and hooks: In my code, there is a MainComponent that has its own operations and content which refreshes whenever the value of props.someData changes. Additionally, I have designed a customized InputFieldComponent. This component generat ...

Perplexing behavior displayed by non-capturing group in JavaScript regular expressions

Here's a straightforward question for you. Regex can sometimes get tricky, so thank goodness for simplifying things... In the URL, there's a query parameter labeled ?id=0061ecp6cf0q. I want to match it and only retrieve the part after the equal ...

Angular DateTime Picker Timezone Directive Problem

Here is a code snippet that displays a date time picker in a form using the angular-moment-picker plugin. The issue I encountered was that after selecting a date/time, the time shown in the input box would be correct, but upon form submission, the time sto ...

What is the underlying mechanism of Angular's $broadcast and $emit for sending message objects - value or reference?

Here is the code snippet for reference: let data = { key1: value1, key2: value2, // more keys }; $scope.$broadcast("EventName", data); When the event consumer receives the data, does it receive a reference to data or a copy? ...

JavaScript with dropdown menus

Currently, I am in the process of implementing a JavaScript code snippet that will be triggered when a checkbox is checked. Once the checkbox is checked, the form should display two additional select boxes. My attempt at coding this functionality was not ...

Executing a jQuery AJAX request for a second time

Upon hitting the submit button for the first time, the codes work successfully. However, upon hitting the button for the second time with correct email and password values, nothing happens and the user cannot log in. I have identified that the issue lies w ...

When testing on jsfiddle, the script functions properly with pure JavaScript. However, when integrating it into my own code, it fails to work unless jQuery is included

Visit this link to access the code snippet. Below is my code: const chk = document.getElementById('chk'); const body = document.body; $(function(){ chk.addEventListener('change', () => { $('.body').toggleClass( ...