Rails API REST post request using AngularJS results in a 400 error indicating a bad request

Hey there, I'm currently working on a project involving Rails API and AngularJs, and I've encountered the following error.

angular.js:11821 POST http://localhost:3000/people 400 (Bad Request)

Unfortunately, I haven't been able to figure out why this error is occurring.

Below is the code snippet:

Rails Controller

 # POST /people
  def create
    @person = Person.new(person_params)

    if @person.save
      render json: @person, status: :created, location: @person
    else
      render json: @person.errors, status: :unprocessable_entity
    end
  end

AngularJS

$scope.SendData = function () {
           // use $.param jQuery function to serialize data from JSON 
            var data = $.param({
                name: $scope.name,
                age: $scope.age,
                gender:$scope.gender,
                lonlat:$scope.lonlat
            });

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

            $http.post('http://localhost:3000/people', data, config)
            .then(function (data, status, headers, config) {
                $scope.PostDataResponse = data;
            })
            .catch(function (data, status, header, config) {
                $scope.ResponseDetails = "Data: " + data +
                    "<hr />status: " + status +
                    "<hr />headers: " + header +
                    "<hr />config: " + config;
            });
        };

Html

<div ng-app="myApp" ng-controller="person">
<div class="modal-body">
<div class="form-group">
<label for="exampleInputEmail1">Name:</label>
<input type="text" class="form-control" name="name" ng-model="name" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputEmail1">age:</label>
<input type="text" class="form-control" name="age" ng-model="age" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputEmail1">gender:</label>
<input type="text" class="form-control" name="gender" ng-model="gender" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputEmail1">lonlat:</label>
<input type="text" class="form-control" name="lonlat" ng-model="lonlat" placeholder="Email">
</div>
<button ng-click="SendData()"
class="btn btn-default">Submit</button>

    {{ PostDataResponse }}

Thank you for your attention.

Answer №1

It seems like the issue might be with your person_params definition not being structured correctly. Typically, when generated by rails generators, you need to ensure that your params are wrapped in a person hash.

var data = $.param({person: 
    { name: $scope.name,
      age: $scope.age,
      gender:$scope.gender,
      lonlat:$scope.lonlat }
});

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

Vue automatically clears the INPUT field when disabling it

Have you ever noticed why Vue resets a text input field when it's set to disabled? This behavior is not observed with plain Javascript and also doesn't affect textarea fields. var app = new Vue({ el: '.container', data: { disab ...

Example of material-ui-pickers: Error - Object(...) is not a function

Trying to implement a basic material UI pickers example using a clean project and following the installation and usage instructions provided here: An error message is displayed as follows: TypeError: Object(...) is not a function Module../node_modules/@m ...

Executing JavaScript code upon clicking a menu item involves creating event listeners for each menu

Currently, I am working on a Squarespace website that includes a navigation bar. I am looking to incorporate a JavaScript code as a link within the navigation bar. The specific JavaScript code is as follows: <div> <script type="text/javascript ...

If the checkbox is selected, retrieve the product name and price and store them in an array

If the checkbox is checked, I want to retrieve the service name and its price in an array. To get the values of the selected items (i.e. service name and its price in an array), please explain how I can achieve this. $(document).on('click', &apos ...

modifying the state in a stateless React component

Hello everyone! I am here trying to work with hooks and I'm not sure how to achieve my goal. Here is the code I have: import React, { useState } from 'react' import { useForm } from 'react-hook-form' import {useDispatch } from &a ...

The functionality of tinymce setContent can only be activated by directly clicking on it

Everything is running smoothly with the code below: $('.atitle').on('click', function(){ console.log('323'); tinymce.get("ed").setContent("<p>lorem ipsum</p>"); // it's working ...

Activate a JavaScript mouse event outside of an element

https://jsfiddle.net/f8L300ug/3/ Attempting to create a drag-to-resize feature, inspired by the provided example. One challenge encountered is that when the mouse is released outside of the <body>, the mouseup event does not trigger as expected. Th ...

"Encountered an issue when attempting to convert undefined or null to an object within a

I am facing an issue with my test setup which looks like this: var jsdom = require('jsdom').jsdom; var document = jsdom('<html></html>', {}); var window = document.defaultView; global.jQuery = global.$ = require('jquer ...

A basic AJAX call in Codeigniter

I am encountering some challenges with ajax and codeigniter. Despite posting a previous question (link to question) and thinking I had resolved it, I am still facing issues. I am seeking assistance in creating simple code using ajax/codeigniter to incremen ...

Obtaining the referring URL after being redirected from one webpage to another

I have multiple pages redirecting to dev.php using a PHP header. I am curious about the source of the redirection. <?php header(Location: dev.php); ?> I attempted to use <?php print "You entered using a link on ".$_SERVER["HTTP_REFERER"]; ?> ...

AJAX: Enhancing Web Pages without Replacing JavaScript

After attempting to replace a section of javascript on my webpage using AJAX, I encountered an issue where it would not replace the content. When I checked the element with the id 'treintracking', I could see the javascript code from the script b ...

In what way does Codesandbox create a resizable grid layout for components?

I am looking for guidance on implementing resizable windows like those in CodeSandbox and VS Code using React. How does CodeSandbox achieve this functionality? Could someone help me get started in the right direction? ...

Table with a responsive c3 chart

Is there a way to integrate a responsive C3 chart into a table? I am trying to set up a table with a responsive layout, where one of the cells contains a C3 chart. The initial dimensions of the cell are 200 width and 50 height, but I want the chart to upd ...

The content of the text does not align. Alert in React 16

Currently, I am working on developing a ReactJs application with server-side rendering. Here are my entry points for both the client and server: client.jsx const store = createStore(window.__INITIAL_STATE__); hydrate( <Provider store={store}> ...

The sorting functionality in AngularJS, specifically the orderBy directive, does not seem to be functioning as expected when using

I've been struggling to understand why my orderBy filter just won't work. I've checked so many solutions, and they all seem to suggest that the issue lies in the fact that my ng-repeat is functioning on an object of objects instead of an arr ...

Can RethinkDB and Node.js/Express handle parallel queries with multiple connections?

Is there a more efficient method for running parallel queries with the RethinkDB Node driver without opening multiple connections per request? Or is this current approach sufficient for my needs? I'd like to avoid using connection pools or third-party ...

Tailoring information to fit selected preferences

Currently working on developing a fitness app with Vue, aiming to create personalized workout routines based on user preferences. Users can choose specific options and generate a workout plan by clicking a button. The collected data is stored as an object ...

Error: ExecJS encountered a problem when attempting to run the code in this ChatRooms

The problem at hand: This is my room.coffee file, and everything is functioning correctly. jQuery(document).on 'turbolinks:load', -> messages = $('#messages') if $('#messages').length > 0 App.global_chat = A ...

Having trouble accessing the height of a div within an Iframe

Here is the issue I am facing: I need my iFrame to adjust its size based on a div within it, but every attempt to retrieve the size of this div results in 0. var childiFrame = document.getElementById("myDiv"); console.log(childiFra ...

Obtain the API response using a Promise.then() in AngularJS

Recently, I've been delving into AngularJS and trying to create a function that deletes a user. The goal is to have the function return a boolean value indicating whether the deletion was successful or not. Despite my best efforts, the promise always ...