Tips for adding responses to input fields in AngularJS

I am looking to populate data into 3 inputs based on the JSON response I receive from my node server. However, despite receiving a response, I am unable to input it into the designated fields.

Controller:

$scope.edit = function(id, contact) {
console.log(id);
$http.get('/contactlist/' + id).then(function(response) {
  console.log(response);
  $scope.contact = response;
});
};  

Server:

app.get('/contactlist/:id', function (req, res) {
 var id = req.params.id;
console.log(id);
   connection.query('SELECT * FROM contactlist WHERE id = ' + id, function (error, results, fields) {
   console.log(results);
   res.json(results);
   });
});

index.html:

<div class="input-field col s4">
    <input id="name" type="text" class="form" ng-model="contact.name">
    <label for="name">Nom</label>
    {{contact.name}}
</div>
<div class="input-field col s4">
    <input id="email" type="text" class="form" ng-model="contact.email">
    <label for="email">Email</label>
</div>
<div class="input-field col s4">
    <input id="number" type="text" class="form" ng-model="contact.number">
    <label for="number">Numéro</label>
</div>

The response displayed in Chrome : View Response Object

Answer №1

the provided answer contains a data array with an object. The first element of the data array holds the contact object.

$http.get('/contactlist/' + id).then(function(response) {  
  $scope.contact = response.data[0];
});

Answer №2

When utilizing the $http service, the resolved object within the then function will include the complete response. This response object not only contains your data, but also additional properties like statusCode and the request configuration. To properly handle this, you should modify your code as follows:

$http.get('/contactlist/' + id).then(function(response) {
  console.log(response);
  $scope.contact = response.data;
});

It is important to access response.data instead of just response. Additionally, on the server side, it's recommended to return only the first result rather than an array of results:

app.get('/contactlist/:id', function (req, res) {
    var id = req.params.id;
    console.log(id);
    connection.query('SELECT * FROM contactlist WHERE id = ' + id, function (error, results, fields) {
        console.log(results);
        res.json(results[0]);
    });
});

Answer №3

Given that you have access to a contact list, my recommendation would be to follow these steps:

$http.get('/contactlist/' + id).then(function(response) {
  console.log(response);
  $scope.contacts = response.data; //make sure to include the 's'
});

For the HTML part, use the following code snippet:

<div ng-repeat="contact in contacts">
    <div class="input-field col s4">
      <input id="name" type="text" class="form" ng-model="contact.name">
      <label for="name">Name</label>
      {{contact.name}}
    </div>
    <div class="input-field col s4">
      <input id="email" type="text" class="form" ng-model="contact.email">
      <label for="email">Email</label>
    </div>
    <div class="input-field col s4">
      <input id="number" type="text" class="form" ng-model="contact.number">
      <label for="number">Number</label>
    </div>
</div>

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

How can I showcase data retrieved from a function using Ajax Datatable?

I have implemented an Ajax function that retrieves data from a PHP file and displays it in a DataTable. Initially, this setup was working fine. However, when I added a new function to the PHP file, my Ajax function stopped retrieving data from the file. I ...

Alert: React-Weather is causing an invalid element type in React

I am feeling overwhelmed. I have created a custom component called react-weather which has been installed using npm. Here is the code snippet for my self-written Weather.js component located in the src/components folder: import React, { Component } from & ...

Issue with Nextjs environmental variables not functioning in JavaScript pages

Currently, I am in the process of developing a Next.js website. Within my JavaScript file, I am fetching data from an API and assigning a token using the .env.local file. However, when attempting to access the .env variable that I've set up, it seems ...

Error message: "Please ensure that you have installed with the -g flag"

I am facing issues with installing Grunt on my computer. Despite following several tutorials and the official installation guide, I am unable to get it up and running. The command line interface installs successfully using the following command: sudo npm ...

What is the process for inserting HTML content into the body of an iframe?

Is there a way to insert HTML content into the body of an iframe instead of using the src attribute to call a page's URL? I am looking for a code that is compatible with all browsers and works perfectly. ...

Tips for adding a new column to a website

My goal is to inject some custom HTML and CSS into YouTube in order to create a column on the right side that shifts all content towards the left. Essentially, I am trying to replicate the functionality of the Inspect Tool in Chrome. I am working on a Chr ...

Using jQuery to locate a JavaScript variable is a common practice in web development

I recently created a JSFiddle with buttons. As part of my journey to learn jQuery, I have been converting old JavaScript fiddles into jQuery implementations. However, I seem to be facing a challenge when it comes to converting the way JavaScript fetches an ...

Send Image Bitmap to Azure Face SDK for detection using the detectWithStream() function

I am currently working on a React application that aims to capture frames from the webcam and analyze them using the Azure Face SDK (documentation). Specifically, I would like to detect faces in the image and extract attributes such as emotions and head po ...

Creating redux reducers that rely on the state of other reducers

Working on a dynamic React/Redux application where users can add and interact with "widgets" in a 2D space, allowing for multiple selections at once. The current state tree outline is as follows... { widgets: { widget_1: { x: 100, y: 200 }, widg ...

Divide the data received from an AJAX request

After making my ajax request, I am facing an issue where two values are being returned as one when I retrieve them using "data". Javascript $(document).ready(function() { $.ajax({ type: 'POST', url: 'checkinfo.php', data: ...

Using JavaScript to generate dynamic folders in Alfresco is not functioning as expected

Working with Alfresco 4.0.d community edition (also tested on Alfresco 4.0.c) on an Oracle Linux 64-bit virtual machine using Firefox. I've been developing a script to dynamically create sub-folders as new items are added to a space/folder via a rule ...

Tips for sending multiple variables to PHP using jQuery

Hello everyone, I could really use some assistance with a jQuery and AJAX issue I'm facing. I admit that I am not very well-versed in these technologies, so it's likely that I am missing something simple here. My problem lies in trying to pass mo ...

Having difficulty installing npm while operating within a corporate proxy

I've exhaustively followed all the steps outlined in this resource: Using npm behind corporate proxy .pac Despite my efforts, I am still facing issues installing webpack and babel. According to suggestions, I downloaded npm from nodejs. However, ev ...

The list in Jquery UI Autocomplete is not updating correctly

Currently, I am using jQuery UI Autocomplete in conjunction with WebSockets to fetch and display a list of options. Each time a keystroke is detected on the input field (.keyup()), a call is made to retrieve the list. However, I have encountered an issue w ...

I am unable to retrieve the variable

Hello there, this is my first time asking a question. Currently, I'm working with NodeJS and Express. Let me share the code snippet: request(urlPrice, function(err, resp, body){ priceInfo = JSON.parse(body), medianPrice = priceInfo.median_p ...

Enhance the functionality of Woocommerce email notifications by incorporating a customized VAT field

I have exhausted all options and tried various email hooks without success. I inherited an outdated PHP code that was developed by someone else, which I updated for new woocommerce hooks (since the code is 4 years old). Everything is functioning smoothly e ...

Showing an in-depth ngFor post on the screen

I am in the process of building a Blog with Angular 7, MongoDB, and NodeJS. Currently, I have developed a component that iterates through all the posts stored in the database and showcases them on a single page. <div class="container-fluid"> < ...

I possess a collection of server-side questions and answers. How can I display them one by one in an EJS template upon clicking?

Here is the path I have chosen: app.get('/test', (req,res)=>{ res.render('index.ejs',{qData: [{Q1},{Q2},...]}); }) Is there a way to display this qData sequentially on the client side with each click? Imagine I have two buttons la ...

How can we start a new session upon signing up using cookie-session and passport.js?

Currently, I have set up a /register router specifically for signing users up. In order to keep things simple right now, I am utilizing cookie-session instead of express-session. However, I've hit a roadblock when it comes to authenticating a user du ...

Utilizing Regular Expressions to Extract Route Parameters in Express.js

After reading through various documents and blogs, as well as this particular question and others, I have learned that one can validate route parameters using regular expressions. Despite this knowledge, I have spent about an hour and a half searching for ...