retrieving serialized object from an ajax request sent to the web server

As a newcomer to web development, I decided to create an ASP.NET project with a web API to test my skills. In the process, I crafted a controller and some JavaScript files as follows:
Controller:

 namespace MyNamespace.Controllers
    {
        public class PairController : ApiController
        {
            public Point Get([FromUri]int rows, [FromUri]int cols)
            {
                return new Point(rows, cols);
            }
        }
    }

JS:

var api = 'api/Pair';
var question = '/?rows=' + $('#rows').val() + '&cols=' + $('#cols').val();
var url = api + question;
$.getJSON(url, function (data) {
    alert('success');
    console.log(data[0].X + ' ' + data[0].Y);
}).fail(function () {
    alert('error!');
});

Upon checking the console, I noticed two 'undefined' lines instead of the expected values from the input fields for rows and cols.
I presumed that the server would serialize the point into JSON format and send back the answer:

{
     "X": value from rows input,
     "Y": value from cols input,
     "IsEmpty": something 
}

Answer №1

Attempting to access the first item of an array by writing data[0].X may lead to confusion. The back-end is not returning an Array of Points (List<Point>), but a single Point object. As a result, it is serialized as follows:

{
     "X": value of rows input,
     "Y": value of cols input,
     "IsEmpty": something 
}

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

What is the best way to exclude fields when unmarshalling JSON in a Golang application?

In my program, I utilize a JSON file to set up the arguments and also use the flag package to configure the same arguments. Whenever an argument is parsed by both the JSON file and the flag at the same time, I prefer to use the argument parsed through the ...

Extracting data from JSON using abstraction in Scala

Looking for an efficient way to extract data from JSON using the 'json4s' library. Imagine having a case class named 'A' and JSON data in this format: case class A(a1: String, a2: String, a3: String) {"a1":"xxx", "a2": "yyy", "a3": " ...

Is it possible to detect if a user has canceled a download in ASP.NET file downloads?

I have a web application built using ASP.NET that allows users to download files from the server. I keep track of the downloads and have restrictions on how many times a file can be downloaded. When users click a button, the following code is executed to ...

Tips for Resizing google reCAPTCHA

The problem's image is shown below: https://i.sstatic.net/ph2EX.jpg Below is the code snippet related to the issue: <div class="text-xs-center" id="DIVCATCHA" runat="server"> <asp:HiddenField runat="server" ID="hdnImageSelected" /> ...

Embed Vue applications within the container of the main Vue application

My goal is to establish a foundational Vue application that offers essential features such as signing in, navigating with a sidebar, and the flexibility to interchange navbar items. I envision creating separate Vue applications for each navbar item. Main ...

Failed to retrieve values from array following the addition of a new element

Does anyone have a solution for this problem? I recently added an element to my array using the push function, but when I tried to access the element at position 3, it wasn't defined properly processInput(inputValue: any): void { this.numOfIma ...

Ways to transfer variables between JavaScript files using a deferred function

I am encountering an issue while trying to retrieve a json object from another JS file. It appears to be a timing problem as the setTimeout function I added runs twice; first with the object correctly populated, and then again with the object becoming unde ...

The app's connection issue persists as the SDK initialization has exceeded the time limit

We are currently facing an issue when trying to publish a new manifest for our app in the store. The Microsoft team in India is encountering an error message that says "There is a problem reaching the app" during validation. It's worth noting that th ...

A method to use jQuery to replace newlines with commas in user input

Input Processing Challenge <input> Whenever there is multi-line text pasted into the input field, I need to replace newlines (\r, \n, and \r\n) as well as tabs \t with commas ,. This scenario mainly occurs when users copy c ...

Base adapter class returning null when displaying JSON data in list view

Hello everyone, I've encountered an issue while trying to display a list of JSON data in a ListView. I have successfully fetched the data but am struggling to append it in the list. To display the data, I created a class that extends BaseAdapter. Howe ...

An issue observed in ASP.NET MVC is that when using the $.post() method, it inadvertently assigns a different controller name to

My ASP.NET MVC application is giving me trouble when I use the $.post() method. This particular method takes the controller name and action name as parameters, like so: "Controller/Action". The issue arises when the post method inexplicably adds the contro ...

An issue with npm arises on Windows 10 insider preview build 14366

It appears that npm and nodejs are experiencing issues on the latest Windows version build 1433 When I ran the following command: npm -v events.js:141 throw er; // Unhandled 'error' event ^ Error: This socket is closed. ...

Changing SVG containing image tags into HTML canvas

I'm attempting to convert an SVG file to an HTML canvas, and everything works perfectly until I introduce the image element in the SVG. When I include image elements, the canvg function stops working. Below is the code I used to convert the SVG to ca ...

Tips for successfully passing array index as an image source in Vuejs with v-img?

Hi there! I'm currently attempting to cycle through an array of URLs and insert them into the src attribute. I'm struggling with the correct syntax to accomplish this task. Would you be able to lend a hand? I have an array named DataArray that co ...

Leverage environment variables in React JS to define distinct API URLs for production and development environments

For my React app, I started with create-react-app as the boilerplate. To make a request to my local server, I'm using fetch. fetch("http://localhost:3000/users") .then(function(res){ return res.json() }) .then(function(res){ return res.data }) ...

Webpack has no issues building the files, however, the JavaScript fails to execute during runtime

I recently upgraded from Webpack v4 to v5, following the documentation and addressing any deprecation messages from the CLI. The build was successful, but when testing the application, I noticed that the JavaScript wasn't running and no errors were be ...

Disable hover effects in CSS with JavaScript

I am looking for a way to deactivate CSS hover functionality using JavaScript. Within a form, there is a button that sends data to the database server. By utilizing OnClientClick() of an ASP.NET Button control, my goal is to modify the text of the element ...

The code snippets in the Vue3 documentation are quite peculiar

As I peruse the Vue 3 documentation, I notice a recurring pattern in how example code is presented for components: Vue.createApp({}) However, my experience with Vue 3 has been different. Instead of the above syntax, I simply use: <script> export d ...

Enhancing an existing node by adding a new node with jQuery functionalities at the same time

Is it possible to append a node to a parent node while also manipulating the node being added? I initially believed this could be done in one step: //I though this was possible: $('#master').after('<div id="test" style="border:solid 1px ...

The sticky header is malfunctioning due to a null offsetTop value

import React , {useRef, useEffect} from 'react' import './header.css' const nav_links =[ { path:'#home', display:'Home' }, { path:'#about', display:'About& ...