Showing JSON response on an HTML page using AngularJS

I have limited experience with JavaScript and/or Angular, but I am required to utilize it for a research project. My task involves showcasing the JSON data returned by another component on a webpage.

Here is how the process unfolds:

When a user clicks on the Submit button on the user interface, a JSON file is sent to another component which processes it and generates a response in JSON format. This response JSON needs to be displayed on a webpage.

The Submit button appears on a page named page2.html:

<button name="topage1" class="button-submit" ng-click="generateJSON()">Submit</font></button>

The generateJSON() method includes the following code:

$scope.generateJSON = function(){
   generateIdForComponents();
   addRestrictions();
   
   // REST
   data = angular.toJson($scope.schema, true);
   headers= {
     'Content-Type': 'application/json',
     'Cache-Control':'no-cache',
     'Access-Control-Allow-Origin': '*'
   };

$http.post('http://127.0.0.1:5000/re/z3', data, {headers:headers}).
    then(function(response) {
        console.log("Merge post ", response.data);
        $scope.greeting = response.data;
    });
}});

The routing setup looks like this:

app.config(function($routeProvider) {
  $routeProvider
  .when("/topage1", {
      templateUrl : "page1.html",
      controller : "page1Controller"
  })
  .when("/topage2", {
      templateUrl : "page2.html",
      controller : "page2Controller"
  })
  .when("/results", {
      templateUrl : "outputOffers.html",
      controller : "resultsController"
  })
  .otherwise({
      templateUrl : "page1.html",
      controller : "page1Controller"
   });
});

What steps should I take to ensure that the JSON data is correctly displayed on outputOffers.html?

Answer №1

If you want to display the response json data on a separate page after generating it in your $scope.generateJSON method, I recommend redirecting to the outputOffers results page and passing the json data as a parameter.

In the resultsController, you can then assign this passed json data to a variable like $scope.greeting, which can be used in your outputOffers view.

To pass parameters between views, make use of the routeParams service and inject it into your resultsController.

Add the $location service in your page2Controller for redirection purposes by injecting it alongside $scope:

myApp.controller("page2Controller", function($scope, $location){... 

Your generateJSON method within the page2 controller should include actions like generating components ID, adding restrictions, converting data to JSON format, and making an HTTP post request with appropriate headers. Upon successful data retrieval, redirect to the results page while passing the json data as a parameter using $location.

resultsController

Don't forget to inject the $routeParams in your resultsController to capture any parameters sent via the URL:

myApp.controller("resultsController", function($scope, $routeParams){...

In the resultsController, check if the jsonData parameter exists (sent from page2) before assigning it to $scope.greeting. This allows proper handling based on whether the parameter is present or not.

(function() {
  if($routeParams.jsonData == null || $routeParams.jsonData === ""){
    $location.path('topage2'); // Redirect to page2 if jsonData is missing
  } else {
    $scope.greeting = $routeParams.jsonData; // Assign jsonData to scope
    console.log($scope.greeting); // Log the data for verification
  }
})();

Utilize the $scope.greeting variable in your outputOffers.html view to display specific properties from the json object:

<p>{{greeting.title}}</p>
<p>{{greeting.message}}</p>

Update:

Based on the snippet of your json provided, iterate through the json data in the outputOffers.html view using ng-repeat:

<div ng-repeat="g in greeting"> 
  <p>id: {{g.id}}</p>
  <p>clockspeed: {{g.offer.clockSpeed}} </p>
</div>

Answer №2

To enhance the functionality, consider creating a service with two distinct functions - one for storing and another for fetching values. The function responsible for storing the value can be integrated into the 'page2Controller', while the function for fetching the value should be placed in the resultsController.

Check out this brief tutorial to guide you through:

app.config(function($routeProvider) {
  $routeProvider
  .when("/topage1", {
      templateUrl : "page1.html",
      controller : "page1Controller"
  })
  .when("/topage2", {
      templateUrl : "page2.html",
      controller : "page2Controller"
  })
  .when("/results", {
      templateUrl : "outputOffers.html",
      controller : "resultsController"
  })
  .otherwise({
      templateUrl : "page1.html",
      controller : "page1Controller"
   });
});

app.service('greetingService', function() {
    this.greeting = '';
    this.store = function (greeting) {
        this.greeting = greeting;
    }
    this.fetch = function () {
      return this.greeting;
    }
});

For instance, here's how the page2Controller should be structured:

app.controller('page2Controller', function($scope, greetingService) {
  $scope.generateJSON = function(){
   generateIdForComponents();
   addRestrictions();
   // REST
   data = angular.toJson($scope.schema, true);
   headers= {
     'Content-Type': 'application/json',
     'Cache-Control':'no-cache',
     'Access-Control-Allow-Origin': '*'
   };

$http.post('http://127.0.0.1:5000/re/z3', data, {headers:headers}).
    then(function(response) {
        console.log("Merge post ", response.data);
        greetingService.store(response.data);
    });
}});
});

The resultsController implementation would resemble the following:

app.controller('resultsController ', function($scope, greetingService) {
  $scope.greeting = greetingService.fetch();
});

Lastly, remember to include this snippet in your 'outputOffers.html' file:

{{greeting}}

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

Tips for dealing with event bubbling in React

Looking for a way to add an onBlur event to the left panel so that it closes when the user clicks on the right panel. I attempted using onMouseLeave but the closing animation isn't as smooth as desired. Additionally, I'd like for users to close t ...

Stop unauthorized users from accessing the static content of an ASP.NET - MVC application

Our application is built with asp.net MVC and angular, utilizing identityserver3 for access control. Although everything else is functioning properly, we have encountered an issue where unauthorized users can still access the static content of the applicat ...

JavaScript tutorial: Removing spaces in column names and creating case-insensitive queries

This morning, I encountered an issue while working on a web app that I am currently developing. The app is designed to read data from an excel file and import it into a SQL table. During the basic validation process, I noticed that the column headers in ...

Looking for a JavaScript code to create a text link that says "submit"?

Here is the code I have, where I want to utilize a hyperlink to submit my form: <form name="form_signup" id="form_signup" method="post" action="/" enctype="multipart/form-data"> ... <input type="submit" value="Go to Step 2" name="completed" /> ...

"Upon loading the page, I encounter JavaScript errors related to Angular's ngOnInit function. However, despite these errors,

I have a page in angular where I am loading data in the ngOnInit function. The data loads correctly and is displayed on the page, everything seems to be working fine. However, I am encountering numerous javascript errors in the console stating cannot read ...

What could be causing the fluctuation in ui-grid height as I scroll horizontally?

After using ui-grid in numerous projects without any issues, I recently encountered a strange issue when working with a large number of columns. With approximately 50 columns, as I scroll from left to right in order to view the columns that are off-screen ...

Implementing AJAX to dynamically insert content into div elements on the page

Currently facing a small issue with my AJAX implementation for creating comments on posts. The functionality is working well, but the problem arises when executing it in the index.html.erb view. The create.js.erb file locates the initial div labeled "comme ...

Does the Array Splice method always remove an item from the end?

I'm having trouble with deleting an item from an array using Array.splice. It seems to always delete the item from the end instead of where I want it to be removed. I'm working with Vue.js and dynamically adding items to an array, but when I try ...

Is there a way to get Axios to display CSS on the page?

While working on a Web Viewer project with axios for web scraping practice, I encountered an issue where the CSS wasn't loading properly. Here is the code snippet I used: console.log("Tribble-Webviewer is starting!") const express = requir ...

Pattern matching for a string with numerous repetitions using Regular Expressions

There's a [tree] and a cat and a [dog] and a [car] too. I am looking to find the words inside each set of square brackets. The resulting array will be tree, dog, car My attempt at using match(/\[(.*)\]/g) didn't work as expected. It ...

What steps should I follow to create an automatic image slider using Fancybox that transitions to the next slide seamlessly?

*I've recently ventured into web design and am currently experimenting with Fancybox. I'm interested in creating a slider with 3 images that automatically transitions to the next image, similar to what is seen on this website: Is it feasible to ...

What is the process of compiling TypeScript code?

When attempting to use tsc, I encountered issues. Even when having typescript but lacking tsc, the problem persisted. What steps should I take next? https://i.sstatic.net/Djgqb.png ...

Ensure all fields are valid prior to performing an update

I'm currently faced with the challenge of validating my form data before executing an AJAX update. Essentially, what I want to achieve is to validate the input data in the form before triggering the ajax update function. I'm unsure about where to ...

Issues arise when props do not get transferred successfully from the getStaticPaths() to the getStaticProps

I have successfully generated dynamic pages in nextJS from a JSON using getStaticPaths(). However, I am facing an issue where I am unable to access the information within the JSON. I pass it as props to getStaticProps(), but when I try to console log it, i ...

initial render results in undefined data

function Story() { let { id } = useParams(); const pin = useSelector(state => state.pins.pin); const dispatch = useDispatch(); const userid = 2 useEffect(() => { dispatch(getPin(id)); }, [dispatch, id]); return ( <div classN ...

`Optimizing Performance using jQuery Functions and AJAX`

As someone exploring ajax for the first time, I'm eager to learn how to write jQuery code that ensures my simple functions like slideshows and overlays still work smoothly when a page is loaded via ajax. Currently, I am implementing the following met ...

bridging information from tables with text fields in forms

I am working on an HTML/CSS page that utilizes a table layout filled with buttons to mimic a T9 keypad design. Within the page, I have a form containing two text fields. My aim is to populate these text fields with numbers based on the values from the tab ...

What sets canvas and webgl renderer apart in the world of three.js?

Attempting to showcase a sphere using three.js, but encountering issues when rendering with canvasRenderer due to the appearance of grey lines on the sphere. View the code here: http://jsfiddle.net/jzpSJ/ See the screenshot here: However, when rendering ...

Using template expressions to access properties that contain spaces

Here is the code structure that I am working with: "name": { "age": [ { "data": { "how old": "23" } }, One of my JSON keys has a space in it. How can I access this pr ...

Incorporating CASL with the latest version of Angular, version

I'm currently working on implementing CASL into my Angular application, but I'm having trouble understanding how to integrate it. // Login Component ngOnInit() { var jsonBody = {}; jsonBody['email'] = 'peter@klaven'; ...