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

Utilizing AngularJS to retrieve associated information from users via a JSON API

I'm currently utilizing the Ionic framework and my inquiry relates to AngularJS. I've set up a JSON API using Ruby on Rails and for authentication, I've opted for ng-token-auth + devise-token-auth. User JSON: { "data": { "id": "1", ...

Incorporating an external library into a Node.js virtual machine

I'm currently working on a nodejs library that enables users to write and execute their own JS code. Here is an example: var MyJournal = Yurnell.newJournal(); module.exports = function(deployer) { MyJournal.description = "my first description& ...

Working with Ruby on Rails by editing a section of embedded Ruby code in a .js.erb file

Currently, I am in the process of developing a single-page website and have successfully implemented ajax loading of templates to insert into the main content section. However, I am encountering difficulties when trying to do this with multiple templates u ...

Displaying a loading template within an Angular component

While reviewing some code in AngularJS version 1.2.22, I came across the following snippet in the HTML: <div class="mainContent" ng-include="content"> </div> Within its corresponding controller, I found this: $scope.content = 'templates ...

Updating all the direct components within the corresponding category with jQuery

Here is the HTML content I am working with: <li class="info"> info<li> <li class="other"> info<li> <li class="other"> info<li> <li class="Error"> error<li> <li class="other"> error<li> < ...

Encountering 401 unauthorized error in Laravel Passport, Vue.js, and Axios integration

I am fairly new to VueJS and I am trying to retrieve data from a Laravel (passport) API. To do this, I have used npm i axios for making API requests. Below is the script code from my App.vue file: import axios from 'axios'; export default { da ...

Unveil the power of the "Enter" key with these jQuery hacks

Is there a way to prevent the Enter key from being counted as a character when disabling the submit button until something is entered in a TextArea? This functionality is achieved using the Count.js.coffee script. $(document).ready -> $(".cmnt_btn") ...

Utilizing the .add() method in Firebase Cloud Firestore for working with nested

In the documentation for Firebase, it mentions updating nested objects. You can find out more about this here: https://firebase.google.com/docs/firestore/manage-data/add-data#update_fields_in_nested_objects Here is my data structure: let ref = db.collect ...

Tips for generating JSON data in the correct format dynamically while continuously adding new information to the existing object

In my form, users input their email and password, which then generates dynamic JSON upon submission. However, I encountered an issue where the JSON gets corrupted when logging in with different user details as it updates the existing JSON with a new object ...

Encountering problems during the installation of Ionic - Error code 'EPROTO'

After attempting to install Ionic on my system, I encountered the following error message: npm ERR! code EPROTO npm ERR! errno EPROTO npm ERR! request to https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz failed, reason: write EPROTO 0:er ...

Unable to receive Ajax response

My current programming setup involves using a combination of JavaScript and PHP to implement an Ajax code. However, at this point in time, the outcome is showing up as undefined. To circumvent this issue, I have resorted to utilizing localStorage to trans ...

Closing md-tooltip automatically after a specified timeout period

I've set up md-chips in Angular material with the following configuration: <md-chips md-chips-disable-input ng-model="session.participants"> <!-- Chip removal button template --> <button md-chip-remove class ...

Clear the local storage once the URL's view has been fully loaded

When retrieving details of a specific item by passing URL parameters stored in local storage, I encountered an issue. I need to delete the local storage variables after the view is loaded. However, what actually happens is that the local storage variable ...

Divs sliding out of alignment

I am experiencing an issue with the scrolling behavior of a wrapper div that contains two nested divs. Specifically, when I scroll the wrapper horizontally on Android devices, the header section and content section seem to be out of sync and there is a not ...

Tips on how to display a Vue component on a new page with Vue.js router

My current challenge is getting my App to render on a new page instead of the same page. Despite trying render: h => h(App), it still renders on the same page. This is the Vue file (Risks.vue) where the router will be linked: <router-link to="/risk ...

What is the process for adding a Contact Us page to a website?

I recently created a website using html, css and Javascript. I would like to include a 'get in touch' page where visitors can send me messages directly on the site. What steps should I take to make this happen? Is it necessary to set up a databas ...

Achieving successful content loading through AJAX using the .load function

Our website features a layout where product listings are displayed on the left side, with the selected product appearing on the right side (all on the same page). Initially, when the page loads, the first product is shown on the right. Upon clicking a new ...

Exploring the process of sending a post data array from Angular to retrieve data on a Laravel API platform

I am working on an Angular project and I have the following code with an array: myArray: [{"kode":"123","nama":"satu dua tiga"},{"kode":"321","nama":"tiga dua satu"}] Now, I need to send this data using a POST request: $http({ method: 'POST&ap ...

Is it permissible for me to incorporate a package from the dependencies listed in the package-lock.json file into my

I'm looking to incorporate date-fns into my project. I currently have react-datepicker, which also uses date-fns. Can I simply utilize date-fns from react-datepicker, or do I need to install it separately in my project? ...

I have the ability to see HTTP-only cookies within my web browser

So, I always believed that httpOnly cookies could only be accessed during a http request. But the other day, while inspecting Firefox dev tools, I noticed that I could actually view the cookies' values. Is this standard behavior? ...