using Angular controller to send JSON data to MongoDB

I am trying to send json data from html using an angular controller to mongodb. However, the data displayed in mongodb is not what was expected. The desired outcome is to see the data entered into the textarea exactly as it appears.

[{"id":"1","name":"service type text","type":"password","value":""}]

This is my html code:

<div ng-app="app" class="ng-scope">
<div ng-controller="sendJsonController" class="ng-scope">
<textarea id="inputFields" rows="4" cols="50" ng-model="input"></textarea><br> 
<input ng-click="senddata" type="button" value="submit"><br>
 </div>  
</div>

--- AngularJS Controller ---

var app = angular.module('app', ['ngRoute']);
app.controller('sendJsonController',
    function senddata($http, $scope) {
        var string = $scope.input;
        console.log($scope.input);
        var json=angular.toJson(string);

        $http.post('fields/addFields', json).success(function (msg) {
            $scope.status = msg;
        });
    });


The output displayed in the mongodb console is:
 [{"_id":"55d9df5fd7ee17b83142829a"}]

Expected Output:

 [{"id":"1","name":"service type text","type":"password","value":""}]

Answer №1

<div ng-app="myApp" class="ng-scope">
 <div ng-controller="submitDataController" class="ng-scope">
  <input type="text" id="nameInput" ng-model="formData.name">
  <input type="text" id="typeInput" ng-model="formData.type">
  <br> 
  <input ng-click="submitFormData(formData)" type="button" value="Submit Data"><br>
 </div>  
</div>

In the controller file

var myApp = angular.module('myApp', ['ngRoute']);
myApp.controller('submitDataController', ['$http', '$scope',
function($http, $scope) {
    $scope.submitFormData = function (formData) {
      $http.post('data/submitData', {name: formData.name,
        type: formData.type}).success(function (response) {
          $scope.message = response;
        });
    }
}]);

The current setup requires inputting all data into one textarea box without sending a JSON object. To send separate data entries, such as "row1 - name, row2 - type", additional logic is needed to split and organize the data before submitting it as an object like {}. For example, converting the entries into an object like {"row1": "name", "row2": "type"}.

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 PassportJS page does not redirect to the login page

Hey there, I really appreciate any help you can provide! I'm currently exploring PassportJS and attempting to implement a user sign up and login functionality. I followed this tutorial closely but have some doubts regarding step 12. https://github.com ...

Creating a JSON data file by extracting information from an Oracle 10g database through SQL

Is there a way to create a JSON API that allows me to retrieve Oracle 10g data using SQL in JSON format? I am aware that JSON_Object was introduced in Oracle 12C R2, but I currently have Oracle 10g and need to access my database data in JSON format. ...

Error: Attempting to access 'props' property of undefined when clicking on a button within a React application leads to a TypeError

I'm currently working on implementing two buttons that will enable navigation to different pages within my React app. However, I encountered an error when attempting to use the button labeled "home." TypeError: Cannot read properties of undefined (rea ...

Trouble with jQuery click event on dynamically generated elements

I have a jQuery function that iterates through each element inside a specified div (#container) and triggers a JavaScript alert whenever a span is clicked. Everything functions correctly when the spans are static. However, when I include code like this: ...

Executing Python scripts with libraries using Node.js

A Node.js application I have in place conducts GET requests to an API every minute. The acquired data is then stored in a MongoDB database. Simultaneously, the Node.js app initiates and runs a Python script using the Keras library on this data at the same ...

Troubleshooting issue with JavaScript sorting function failing to arrange elements in ascending

I'm having trouble sorting numbers in ascending order using JavaScript. Here's the code snippet: <h2>JavaScript Array Sort</h2> <p>Click the button to sort the array in ascending order.</p> <button onclick="myFunctio ...

Using jQuery to import certain library causes the XPage to completely lock up

My XPage only relies on 2 js imports - one being JQuery and the other dependent on JQuery specifically for smart companies search in the Russian Federation. However, a challenge arises when trying to import the second library as it causes the entire page t ...

JavaScript: Locate web addresses within a block of text and convert them into clickable hyper

How can we convert the following PHP code to JavaScript in order to replace URL links inside text blobs with HTML links? A jsfiddle has been initiated. <?php // The Regular Expression filter $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a- ...

Is there a way to create a textbox input that provides autocomplete/autosuggest but displays only the first match directly within the textbox instead of showing a list?

While I came across several autocomplete/autosuggest samples, none of them quite fit what I'm looking for. Instead of displaying a list below the textbox that requires clicking or selecting, I want to show the closest match inside the textbox itself a ...

Automatically submitting a form in React.js based on certain conditions being met

Does anyone have experience with React login and register form buttons that trigger Redux actions? I'm facing an issue where both actions are being dispatched at the same time when certain conditions are met. Here is my code snippet: const LoginPage ...

Working with varying amounts of JSON data in REST services

I need to consume a REST web service with JSON type where the input JSON has a different number of values each time. For example: {"name":"x","age":23,"language":"java"} or {"name":"c","age":"34","language":"c++","db":"oracle"} The input JSON may vary ...

What is the process for accessing a local JSON file within our Vue application if we are utilizing a CDN link for Vue?

Having trouble using a local JSON data file in a Vue app while also utilizing a CDN link for Vue. Any suggestions on how to make this work? Need assistance as my attempts to access the JSON file have been unsuccessful. ...

Repeated saving of CoreData relationship pair

I am facing an issue with a "Listing" entity that has a relationship to many "Tags". I am saving the data using JSON as shown below: func saveData(context: NSManagedObjectContext) { for listing in listings { ...

Pass information from the view to the controller, and then relay it to a different view

I'm working on passing a variable to a controller and then utilizing that variable in another view. In View1.html: var cat = 5; Controller.js: // retrieve the cat=5 variable In View2.html: // also retrieve the cat=5 variable from the controller Vi ...

Title of a design pattern: Transferring information between programming languages

I am trying to determine the name of this pattern, if it exists. It involves taking data from one programming language and using it in another. For example, PHP to Javascript. Initially, I thought it could be delegation, but I have seen this process done b ...

How to capture mouse events using a personalized directive in Angular

One of my projects involves a custom directive named side-menu, which I include in my index.html like this: <side-menu></side-menu> This directive contains a controller that is located in a separate file (SidebarController.js). The template f ...

Is there a way to activate a freshly duplicated Bootstrap select field?

I am attempting to duplicate a bootstrap select field and immediately open the duplicate. The following code toggles the original select field. $('.selectpicker').selectpicker("toggle"); However, when I try to toggle the duplicated field, it i ...

Unraveling the Mysteries of AngularJS in a Tutorial Snippet

After reading through the enlightening theory snippets in Step 3 of AngularJS Tutorial, one particular passage piqued my curiosity: The scope, which connects our controller and template to create a dynamic view, is not isolated within its own bounda ...

Choose an option from the dropdown menu to reveal the selected item

Consider a scenario with the following select HTML element: <select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select& ...

After successfully installing an SSL certificate on my nginx server, attempting to access the URL in the browser only results in an error message: ERR_CONNECTION

Running a Node.js application on port 3000, I set up nginx to redirect traffic from port 80 to 3000 using the command: sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3000 I have my domain name assigned as okium.fun. Ad ...