Show the JSON response from the controller on the view page

In my controller, I have a JsonResult action that returns a list of House objects. My goal is to retrieve this data onclick using ajax and display the JSON data within my view. While I can see the proper response and JSON result in Firebug, I'm not sure how to display it in my view.

function FetchData(id) {
    $.ajax({
        url: ('/Home/FetchData'),
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ id: id }),

        success: function (result) {
           // attempted parsing but didn't work
           // result = jQuery.parseJSON(result);
           // alert(result.Title);
        },
        error: function () { alert("error"); }
    });
}

public JsonResult FetchData()
{
   ...
   var temp = getMyData...
   return Json(temp, JsonRequestBehavior.AllowGet);   
}


  // View page
     <div id="showContent">
       // JSON data should appear here
     </div>

In Firebug's JSON tab, when success:function(result) is empty, the following data is displayed:

Id  149

PropertyType    "Apartment"

StreetNumber    "202B"

CityName        "Sidney"

Title           "My test data"

Answer №1

onSuccess: function (jsonData) {
  var content = null;

  $.each(jsonData.entries,function(entry,index){
    content = '<span>'+entry.code+ ' | ' + entry.name +'</span>';    
    $("#displayArea").append(content);
 });

}

Answer №2

To start with, when making your ajax call, you can set the dataType attribute to 'json' so that you won't have to decode the json response again -

dataType: 'json'

By doing this, there is no need for parseJSON. You can simply access result.Title directly.

 success: function (result) {
           alert(result.Title);
           var showContent = $('#showContent');
           showContent.html(result.Id+','+result.Title);
        },

Answer №3

UPDATE: Just like Mukesh mentioned, the ajax function has the capability to return json without the need for additional decoding steps.

The result of the ajax call is already in object form. You have full control over how you want to manipulate it within the success function.

One possibility is creating a dynamic table displaying the information directly inside the function, or passing the data to another function by invoking it from within the success function. Once you exit the success function, the data becomes inaccessible.

Access the data object similar to any other object (data.someProperty).

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

Interactive pop-up window featuring conversational chat boxes

Trying to create a comment box within a Modal dialog box that is half of the width. The comments in this box should be read-only and created using div tags. Attempted reducing the width and using col-xs-6, but ending up with columns spanning the entire w ...

Having difficulty executing the Cypress open command within a Next.js project that uses Typescript

I'm having trouble running cypress open in my Next.js project with Typescript. When I run the command, I encounter the following issues: % npm run cypress:open > [email protected] cypress:open > cypress open DevTools listening on ws: ...

Is there a way to manually trigger a re-render of all React components on a page generated using array.map?

Within my parent component (Game), I am rendering child components (Card) from an array. Additionally, there is a Menu component that triggers a callback to Game in order to change its state. When switching levels (via a button click on the Menu), I want a ...

Ajax produces a complete reload of the page

I have been working on implementing Ajax functionality to a form that includes a button. The goal is for the form to be submitted when the button is clicked, without causing a page reload. Currently, the issue I am facing is that it reloads the entire pag ...

Troubleshooting Angular 2 Fallback Route Failure

My current project is using Angular 2 Webpack Starter but I am having trouble with the fallback route. In my app.routes.ts file, I have defined the routes as follows: import { Routes } from '@angular/router'; import { HomeComponent } from &apos ...

The UI router experiences a crash and requires a refresh after precisely six clicks

Whenever the following sequence of events occurs, my application seems to malfunction. Upon clicking on a user and assigning them a role, the page refreshes. A separate GET request retrieves a list of all users currently in the class. After selecting ex ...

The socket.rooms value is updated before the disconnection listener finishes its process

When dealing with the "disconnect" listener, it's known that access to socket.rooms is restricted. However, I encountered an issue with my "disconnecting" listener. After making some modifications to my database within this callback, I attempted to em ...

Issue encountered: org.json.JSONException - Index 2 exceeds the accepted range

Hello, I am currently dealing with a simple JSON error that says org.json.JSONException: Index 2 out of range. Can someone help me solve this issue? Here is the snippet of my JSON: [ { "cat_id": 593 "title": "Allergy and Immunology", "sub_cat" ...

Is it possible to save the current permissions for a channel or category in Discord.js and then restore them after a certain event occurs?

A Little Background I recently came across a lockdown command on YT that locks down all channels in the guild when you type "!lockdown". This command overwrites channel permissions for specific roles. However, when we unlock the channels, everyone is able ...

An array is not just a mere collection of elements

I have an object that resembles an array var items = [ { started_time: 2017-05-04T12:46:39.439Z, word: 'bottle', questionId: '161013bd-00cc-4ad1-8f98-1a8384e202c8' }, { started_time: 2017-05-04T12:47:26.130Z, word: &apo ...

Tips for ensuring synchronous state changes in React

I am working on a currency calculator using react.js I am fetching the latest exchange rates and storing them in state using the getRates function: getRates(currencyShortcut){ fetch('https://api.fixer.io/latest?base='+currencyShortcut) ...

Using AngularJS to send data from a controller to a factory

Looking to implement a basic pagination feature with data from the backend. Each page should display 10 activities. /feed/1 -> displays 0-10 /feed/2 -> displays 10-20 /feed/3 -> displays 20-30 The goal is to start at page 1 and increment the pag ...

PHP MYSQL, streamlined alert system

Could someone assist me in removing the notification counts after they have been read or opened? I apologize if the explanation is unclear and for any language mistakes. Here are a sample of my codes: /index.php <script src="http://ajax.googleapis. ...

The interconnected nature of multiple asynchronous tasks can lead to a render loop when relying on each other, especially when

My asynchronous function fetches data in JSON format from an API, with each subsequent call dependent on the previously returned data. However, there are instances where I receive null values when trying to access data pulled from the API due to the async ...

Issues have been identified with the functionality of the Am charts v3 XY in conjunction with a

I'm currently working on a project with angularJS and utilizing the npm package amcharts3 "^3.21.15". I've encountered a minor issue regarding the logarithmic scale in my XY chart. Below is my chart without the logarithmic scale: View working ch ...

Are you trying to incorporate incorrect JSON syntax in Ruby?

I am currently working on a test to confirm that when invalid JSON is included in a cURL request, it results in a 400 error code. However, I am facing an issue where Ruby does not allow the use of invalid JSON. if bad_json credentials = { "username" ...

Convert Query to JSON: Output Each Column Twice with Unique Identifiers

I am working with PHP code to retrieve all payments (payment amount, user name, and payment month) made by various users in different months: $result = $mysqli->query("SELECT p.id as id, p.amount as amount, u.name as user_id, ...

Container holding a Material-UI drawer

Is it possible to set the material-ui drawer inside a container in reactjs? I have wrapped my app page in a container with a maximum width of 600px. I want the drawer to start within that container instead of on the body page (picture). The app bar positi ...

What could be causing my TypeScript code to not be recognized as CommonJS?

I rely on a dependency that is transpiled to ES6. My goal is to leverage ES2019 features in my own code. Ultimately, I aim to output ES6. This is how I set up my tsconfig { "compilerOptions": { "module": "CommonJS" ...

Sophisticated web applications with Ajax functionalities and intricate layouts powered by MVC frameworks

I am looking to integrate an ajax-driven RIA frontend, utilizing JQuery layout plugin (http://layout.jquery-dev.net/demos/complex.html) or ExtJs (http://www.extjs.com/deploy/dev/examples/layout/complex.html), with... a PHP MVC backend, potentially using ...