Handling JSON Data in Ajax Success Function

I am trying to figure out the best way to send a complex object from my Controller Method to an Ajax call. From my research, it seems that using JSON is the preferred method.

This is what my Controller Method looks like:

public JsonResult GetUserByData(string fn, string ln, string dep, string cc, string tel, string mail) {
        IList<Models.Person> userCollection = Models.Person.GetPersonsByData(fn, ln, dep, tel, cc, mail).ToList();
        if (userCollection.Count > 1) {
            return Json(new { Complex= true, HTML = PartialView("SomeView.cshtml", userCollection) });

        }
        else {
            return Json(new { Complex = false, HTML = PartialView("SomeOtherView.cshtml", userCollection.First()) });
        }

And here is my Ajax call:

$.ajax({
            url: 'Home/GetUserByData',
            type: 'POST',
            dataType: 'html',
            data: {
                fn: firstname,
                ln: lastname,
                dep: department,
                cc: costcenter,
                tel: telephone,
                mail: mail
            },
            success: function (data) {
                if (data.Complex)
                    $('#Customer_Person').html(data.HTML);
                else
                    $('#Notification_Area').html(data.HTML);
            }
        });

However, I seem to be having trouble accessing the "Complex" and "HTML" properties in my script. Am I missing something? Is using JSON the best way to pass complex objects, or are there other methods I should consider?

Answer №1

When specifying the return type as HTML (dataType: 'html'), jQuery interprets the response as a string rather than JSON. This means data.Complex will not yield any results. If you were to try parsing the data as JSON, it would likely result in errors since HTML and JSON do not integrate well together. One solution is to return the JSON first and then make a separate call for the HTML, or have the server select the correct template and only send the HTML.

edit: @Savaratkar is right, another option is to encode/escape your HTML and pass it through JSON.

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

Creating a Duplicate of an iframe with jQuery

Hey there, I have a dilemma with two divs. One is for displaying content, and the other is a video player that I want to pause and resume on scroll using jQuery. My goal is to pause the video in the "myplayer" div on scroll and have it resume playing from ...

Encountering issues with postback functionality on an ASP.NET webpage while attempting to integrate Google

Creating a small web app using ASP.NET has been going smoothly, until I encountered an issue with LinkButton controls after adding Google Analytics code to one of my pages. Every time I click on a link button, I receive this error message: Microsoft JSc ...

Understanding the functionality of an array as an index in JavaScript

It was discovered (tested in Chrome) that the index of an array can actually be an array itself: a = [1, 2, 3] index = [1] a[index] // returns 2 Has there been any official documentation confirming this behavior? ...

Convert a web page to PDF with JavaScript when the user clicks on a button

Whenever the user clicks on the GeneratePDF button, the goal is to export the HTML page into a PDF file. The issue at hand is that although the HTML page is successfully exported into a PDF file after the first click, subsequent clicks do not result in dat ...

Sharing image using the MEAN stack

While I've found numerous resources online discussing this topic, none of them seem to present a method that resonates with me. My current setup involves a form with multiple inputs that are sent to the server upon clicking a "Submit" button. This da ...

Progressive Dropdown Options - Multiple Paths

As a newcomer to AngularJS, I have come across various implementations of cascading dropdown lists that do not meet my requirements. I am unsure how to modify or extend them to achieve the functionality I desire. I would appreciate it if you could provide ...

Jest anticipated the mock function would have been invoked

Currently, I am running tests on a specific service. Here is the code snippet for the service: import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { ...

moodle - eliminate the need for grading at the same time

I'm currently setting up a Moodle installation and I'm looking for suggestions on how to prevent simultaneous grading. My goal is to have several evaluators grading students across various courses without any conflicts. If you have any recommend ...

Creating a new column in an SQL query by converting a set of results from another table into an array

Currently, I am facing a challenge in creating a join query that involves two tables and requires including a new column that is essentially the result of a separate query from another table. The catch here is that this new column needs to be stored as an ...

Images mysteriously vanishing after importing the Bootstrap stylesheet

One of the features on my website is a page where, upon hovering over an image, an overlay appears with a caption. Below is the code for one such image: <div id="content"> <div class="mosaic-block fade"> <a targe ...

Pulling information from a JSON file using Angular 2

Is there a way to extract data from a JSON file in an Angular 2 project? I attempted the following code snippet, but it seems to be ineffective. Perhaps I missed some important details... any guidance would be greatly appreciated. Additionally, I aim to s ...

The div is inexplicably shifting downward once the first three rows are shown correctly

After displaying the first 3 rows properly, the div mysteriously moves down. Could I be making a silly mistake? All images have the same width and height. Please see the attached image for reference. <?php // start first row echo "<hr class='m ...

Passing the value in a td element to a JavaScript function using Thymeleaf onClick

Trying to utilize "Thymeleaf" for the first time, I am attempting to pass a value to JavaScript with the following code: onclick="getPropId('${properties.id}')" The corresponding function is as follows: getPropId(inputID){alert(inputId);} Unf ...

Ways to verify the presence of users in the Database

I have successfully retrieved the data with the code below, but I am encountering issues with my script's if and else statements. Any tips or advice on how to improve this functionality? server.post('/like', (req, res,next) => { var ...

The typing library for Angular does not properly identify the JQueryStatic object

Encountered an issue with the Angular declaration file: Error TS2304: Cannot locate identifier 'JQueryStatic'. The typings for jQuery are installed and properly declare JQueryStatic as an interface. Looking for solutions to resolve this error. ...

Generating a new ini file and modifying parameters with the use of Spring MVC

Using ajax, I passed two parameters in my function. @RequestMapping(value = "/tmax", method = RequestMethod.POST) public ModelAndView tmax(@RequestParam("id") String id,@RequestParam("name") String name) { } Once these two parameters are assigned, they ...

Using the "margin: auto" property to center the text box

I am having trouble centering the search box. I tried adding marginLeft: "auto",marginRight: "auto" to the search class but it's not working. Can you please advise me on how to fix this issue? Below is my code snippet and a link to the sandbox: https ...

When visiting this website, a special feature is enabled where the page will automatically refresh every 5 seconds. As the countdown begins, the numbers 5, 4,

Could use some assistance with setting up an HTML page to reload every 5 seconds and display a countdown when the refresh link is clicked. After clicking the refresh link, it should disappear and show a countdown from 5 to 1 before reloading the page aga ...

Issue: Unable to access the 'Stream' property as it is undefined in the AthenaExpress.query function due to a

I'm currently attempting to establish a connection with AWS Athena and run a select query using the athena-express package. However, I encountered the following error: Error: TypeError: Cannot read property 'Stream' of undefined at AthenaEx ...

Accessing elements in a JSON object was straightforward with the

I need help with accessing values from a JSON object based on a key name stored in a variable. My colleague has written a function to extract keys from the JSON object and compare them with the ones we are interested in. However, I am struggling with fig ...