The failure to parse an object in response to a JavaScript AJAX call

Why am I getting undefined in the console?

Javascript code:

var url = "/SitePages/AlertsHandler.aspx/GetAlert";
$.ajax({
    type: "POST",
    url: url,
    data: '{alertId: \"' + alertId + '\"}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        console.log(data.IncidentDesc);
    }
 });

C# code:

[WebMethod]
    public static string GetAlert(string alertId)
    {
        return MyJsonObject; // on debug --> {"IncidentDesc":"assdafsdaf","IncidentRecommend":"asdfsdaf"}
    }

I found the problem:

var data2 = JSON.parse(data.d);
console.log('IncidentDesc:' + data2.IncidentDesc);

Answer №1

give this a shot

var link = "/SitePages/NotificationsHandler.aspx/CheckNotification";
var info={notificationId: notifId};
$.ajax({
    method: "POST",
    url: link,
    data: JSON.stringify(info),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
        console.log(result.NotificationDetails);
    }
});

Answer №2

If your JSON data is returned as a string, you'll need to parse it before accessing specific properties.

let parsedData = JSON.parse(jsonString);

console.log(parsedData.propertyName);

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

Looking to create a pop-up using javascript, css, or jQuery?

When visiting digg.com and clicking the login button, a sleek in-screen popup appears to input user data. I'm curious about the best way to achieve this on my own site. It is built with RoR and includes some Javascript elements. Searching for "javasc ...

Issues with ASP.NET combo box appearance whilst implementing AJAX

Currently, I am in the process of building a website that utilizes Ajax to generate a list of suggestions for an ASP.NET autocomplete combo box. I have successfully populated the list, but when I test the site, it appears as follows: I have relocated the ...

Ensuring Filesize Verification Prior to Upload on Internet Explorer Using Javascript

Can JavaScript be used to verify a file's size before it is uploaded to the server at the client side? This application is developed using EXTJS and Java and is limited to Internet Explorer 7 on Windows XP machines. ActiveX cannot be used. The workf ...

Ways to incorporate margins into text on PDF pages produced by Puppeteer without altering the background color

I am currently using puppeteer to generate PDFs that contain dynamic content. My goal is to include margins/padding above and below the text on consecutive pages. Unfortunately, when I try to add margins with the property margin: { top: "1cm", bottom: "1 ...

Angular Digest Loop for Dynamic Photo Grid Styling

I have a special filter that alters the objects being filtered. However, when I apply ng-style="item.gridSize", it triggers my custom grid algorithm. This algorithm was adapted for my requirements from a source found at this link. angular.module("custom.m ...

How does the 'snack bar message' get automatically assigned without being explicitly defined in the 'data' function?

As a novice in web development and Vue, I am currently engaged in a simple project using Vuetify with Vue.JS 3. Within one of my views, there is a table that triggers a message and fetches status to display a snackbar to the user: methods: { async fetc ...

Encountering an issue while invoking the helper function in Vuejs

Main view: <script> import { testMethod1 } from "../helper"; export default { methods: { init(){ console.log("Res:", testMethod1()); } } } </script> Helper: import DataService from "../services/data. ...

Set markers at specific locations like "breadcrumbs" and generate a route using Google Maps API v3.exp

I'm developing a new iOS application for scouting out locations while on the move. I want users to be able to mark each location by simply clicking a button, which will drop a marker based on their current location. The ultimate goal is to connect all ...

Can you provide guidance on achieving a gradient effect throughout the mesh, similar to the one shown in the example?

Check out my code snippet on JSFiddle: https://jsfiddle.net/gentleman_goat66/o5wn3bpf/215/ https://i.sstatic.net/r8Vxh.png I'm trying to achieve the appearance of the red/green box with the border style of the purple box. The purple box was created ...

Navigating to the bottom of a specific element by scrolling

I am currently working on enhancing a module within the application I'm developing. The goal is to automatically scroll the browser window to the bottom of an element when said element's height exceeds the height of the window. The functionality ...

Storing a collection of objects in session storage

I've been struggling to save an array containing the items in my online shopping cart. Even though both the object and the array are being filled correctly, when I check the sessionStorage, it shows an array with an empty object. I've spent a lot ...

Oops! Make sure to call google.charts.load before calling google.charts.setOnLoadCallback to avoid this error

My HTML file includes the following imports: <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> ...

Ways to effectively test a custom hook event using Enzyme and Jest: A guide on testing the useKeyPress hook

Looking for guidance on testing a custom hook event called useKeyPress with Enzyme and Jest This is my current custom hook for capturing keyboard events and updating keyPress value: import React, { useEffect, useState } from 'react' const useKe ...

Is it possible to access the ID of a collection_select and have a list of items appear whenever the selection is modified?

I am working on a form named _form.html.erb <%= simple_form_for(@exam) do |f| %> <%= f.error_notification %> <div class="field"> <%= f.label :Year %> <%= f.collection_select :year_id, Year.order(:name), :id, :name, ...

Basic HTML Audio Player Featuring Several Customizable Variables

I have a unique API that manages music playback. Instead of playing audio in the browser, it is done through a Discord bot. Achievement Goal https://i.stack.imgur.com/w3WUJ.png Parameters: current: indicates the current position of the track (e.g. 2:3 ...

Having trouble getting PHP Ajax File Upload to function properly?

I am using Bootstrap and have a Form in a Modalbox. There is a Fileupload field, and I want to upload images. However, when I click the Submit button, the site seems to reload instantly and there is no file uploading... Below is my Ajax Script: <scri ...

JavaScript: Issue with launching Firefox browser in Selenium

I'm currently diving into Selenium WebDriver and teaching myself how to use it with JavaScript. My current challenge is trying to launch the Firefox browser. Here are the specs of my machine: Operating System: Windows 7 64-bit Processor: i5 Process ...

Utilize AngularJS ng-repeat directive to refine JSON objects

I'm working on an angular js controller with a json array that organizes countries by continents. Each continent consists of its own array of countries. //CONTROLLER app.controller('CountryController', function(){ this.continents = ...

Changing the border color of a Material UI textbox is overriding the default style

Upon the initial page load, I expected the border color of the text box to be red. However, it appeared grey instead. I tried setting the border color to red for all classes but the issue persisted. Even after making changes, the border color remained unch ...

Finding a specific document in MongoDB using a unique slug within Next.js: A step-by-step guide

I have a collection of data in MongoDB structured like this: [ { "Post": "this is a post", "_id": ObjectId("630f3c32c1a580642a9ff4a0"), "slug": "this-is-a-title", "title" ...