Having trouble connecting retrieved database information with AngularJS for display in the view

I am currently working on extracting data from a database and displaying it in a view using AngularJS. I have created a WEM method for this purpose:

[WebMethod]
public static string fetchNames() {
  SqlHelper sql = new SqlHelper();
  DataTable dt = sql.ExecuteSelectCommand("select cust_F_name from customer");
  Dictionary<string, object> dict = new Dictionary<string, object>();
  object[] arr = new object[dt.Rows.Count];
  for (int i = 0; i <= dt.Rows.Count - 1; i++) {
    arr[i] = dt.Rows[i].ItemArray;
  }
  dict.Add(dt.TableName, arr);
  JavaScriptSerializer json = new JavaScriptSerializer();
  return json.Serialize(dict);
}

To call this method in AngularJS, I use the following code:

var App = angular.module('App', []);
App.factory('DataFactory', function ($http) {
  return {
    getNames: function () {
      return $http.post('Home.aspx/fetchNames', { name: "" });
    }
  };
});

App.controller('DataController', function ($scope, DataFactory) {
  DataFactory.getNames().then(function(data){
    $scope.Names =$.parseJSON( data.d);
  }, function(error){
    // handle errors here
  });
});

The binding in the view is done like this:

<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="App">
  <head runat="server">
    <title></title>
  </head>
  <body data-ng-controller="DataController">
    <form id="form1" runat="server">
      <div>
        Name<input type="text" data-ng-model="Name" />{{ Name }}
        <ul>
          <li data-ng-repeat="name in Names | filter:Name">{{ name }}</li>
        </ul>
      </div>
    </form>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="Script/Home.js" type="text/javascript"></script>
  </body>
</html>

However, the output I am currently getting is not as expected. I am struggling to extract only the name from the JSON object. Any suggestions on how to achieve this would be greatly appreciated.

Answer №1

When using $http methods, expect a promise in return.

It's important to note that promises will invoke callbacks with only one argument.

Therefore, when utilizing the .then(function(customer) { method, the 'customer' variable will actually point to a promise object rather than the response body. This promise object contains the following properties:

  1. data – {string|Object} – The response body transformed with the transform functions.
  2. status – {number} – HTTP status code of the response.
  3. headers – {function([headerName])} – Function to retrieve headers.
  4. config – {Object} – Configuration object used for the request.

Here's the Solution:

DemoApp.controller('SimpleController', function ($scope, SimpleFactory) {
  SimpleFactory.getCustomer().then(function(object){
    $scope.Customer = object.data.d;
  }, function(error){
    // handle errors here
  });
});

You can also utilize success and error. The arguments passed to these functions represent the response object passed into the then method.

For more information, check out the $http documentation.

Answer №2

When the server returns valid JSON, there is no need to use parseJSON. Simply utilize the result that is provided.

$scope.Customer = customerData.d;

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

Using a try block inside another try block to handle various errors is a common practice in JavaScript

In an effort to efficiently debug my code and identify the location of errors, I have implemented a try-catch within a try block. Here is a snippet of the code: for (const searchUrl of savedSearchUrls) { console.log("here"); // function will get ...

What is the functionality of the Poloniex JSON API web links?

For the past few months, I have been attempting to retrieve historical data for a specific pair at 4-hour intervals. A format was suggested to me to fetch this data: Is there a way to specify duration and time interval using the provided links? The link ...

Struggling to display live data in KENDO Dropdown menu

I am encountering an issue when trying to populate data in a Kendo drop down. Here is my code snippet along with the JSON response. Code: $("#sortOrder").kendoDropDownList({ dataTextField: "SORTORDER", dataValueField: "SORTORDER", dataSource ...

Struggling to display filtered content in React using State

As a newcomer to React, I am working on a todo list that shows both current and completed tasks using LocalStorage. Each task has a boolean property called "active" which is toggled when a user clicks on the task checkbox. I have a filter in place to separ ...

GSON threw an error: was expecting BEGIN_ARRAY but encountered BEGIN_OBJECT instead

Hello, I have a specific question regarding parsing a JSON file with GSON. The JSON structure is as follows: { "BUYER": { "IGN": "MGlolenstine", "ProductID": "51" }, "BUYER": { "IGN": ...

Error: JSON data abruptly terminated (Node.js)

As a beginner developer diving into the world of API's, I've encountered a recurring error in Node.js that seems to be causing crashes: SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at IncomingMessage.<anonymo ...

Issue with vue-cli3 eslint and compiler arising from conflicting vue/script-indent settings

Whenever my .eslint.js file includes this rule: "vue/script-indent": [ "error", 4, { "baseIndent": 1, "switchCase": 1, } ] and I save it, an error pops up: Error: Expected indentation of 32 spaces but only found 24 spaces ...

Oops! Looks like there was a mistake: [ng:areq] Argument Controller is Not a Function

I'm currently working on integrating a blank Google Maps app into my Rails project with the intention of adding markers later through factories. This approach was successful in my previous project, however, I am facing difficulties getting it to load ...

Distinguishing div identifiers for jQuery displaying and concealing

Although I am not a coder, I am still learning and trying to improve my skills. I have multiple div elements listed by a MySQL query. I require a JavaScript code that can display the class="qform" div based on which button is clicked. If button-1 is clic ...

How to fetch database results using jQuery AJAX and PHP's JSON encoding

I am currently working on a PHP code that is triggered using jQuery AJAX to query a database and retrieve results, which are then encoded into JSON format. //$rows is another query foreach($rows as $row) { $sql = 'SELECT field1, field2 FROM tabl ...

Getting a JWT token from Express to Angular using ngResource: A step-by-step guide

Currently, I am utilizing a jwt token for user registration validation. A unique URL is generated and sent to the user via email, which leads them to the authentication page. On the server side, the token is decoded and I need to transmit this JSON data to ...

Node.js and Express - Dealing with Callbacks that Return Undefined Prematurely

I've hit a roadblock with this issue that's been haunting me for weeks. The first function in my code queries a MySQL database and returns a response, which is then processed by the second function. The problem lies in the fact that JavaScript ...

Having trouble accessing the POST RESPONSE json in ReactJS and NodeJS

I have set up my own API server that is connected to a MySQL database. Whenever I send a request to the server, everything seems fine. I can see the input from the browser and the output from the database in the console. However, I am unable to see any new ...

Transform the text area in preparation for a GET request

Trying to figure out how to pass the text from a textarea into the source attribute of an image tag while retaining all formatting, including line breaks. After some research, it seems that the best way to accomplish this is by base 64 encoding the text a ...

Script in Javascript halting Internet Explorer's operation

I'm encountering a problem with Internet Explorer freezing due to the following code. This code is part of a project that focuses on handling student grades: var array1 = StudentGradeAreadHugeList(); var nextArrayItem = function() { var grade = ...

Troubleshooting: Node.js not receiving data from HTML form

I am currently facing an issue with my HTML form and Node.js server. Despite implementing a form that is supposed to send data to the server, no information is being transferred. The form successfully makes a request, but it fails to send any form data alo ...

Maintaining the user interface state while utilizing $resources in AngularJS

For my app, users have the ability to create and delete items. I've implemented $resources for this functionality, which is working really well. However, I'd like to implement a loading screen that appears whenever a request is being processed. ...

Error encountered when deploying the app to the live server: 500 Internal Server Issue

I am encountering an issue with my ASP.Net web app's ajax file upload feature. While it works perfectly on my local host machine during testing, I face a 500 Internal Server error when I try to publish it to a website. The console output in Google Chr ...

Error: Access Denied - discord.js bot command cannot be executed due to lack of authorization

Every time I initiate the bot and try to execute my "ping" command, an error occurs: js:350 throw new DiscordAPIError(data, res.status, request); ^ DiscordAPIError: Missing Access at RequestHandler.execute (C: ...

Receiving 'Unexpected end of input' error when using a string as a JavaScript function argument

I am trying to implement an ajax request function in my project. This is the code snippet I have: function Reject(id, scomment) { jQuery.ajax({ type: "POST", url: "reject.php", data: {id: id, Scomment: scom ...