Having trouble with the JSON response - The property of the object it returns is showing as undefined even though I can clearly see that it is

After making an ajax request using a form, I receive a JSON response stored in a variable called response. The structure of the response is as follows:

{
    data: {
      attributes:{
            //list of key-values
        }
        id: null,
        type: "job"
    },
    links: {
      modal: "/client/render/modals/job/success"
    },
    message: "job successfully created",
    success: "ActionSuccess"
}

However, when trying to access response.links.modal or response['links']['modal'], I encounter the following error:

Uncaught TypeError: Cannot read property 'modal' of undefined

I find it confusing that the program does not recognize the existence of 'links', even though I can clearly see it in the JSON response preview (using Chrome).

EDIT:

The code responsible for the ajax request:

function submit_form(request, method, data, type, target) {
    switch(type){
        case 'modal':
            $('#' + target).openModal();
        break;
        case 'target':

        break;
        case 'page':

        break
    }
    $.ajax({
        url: request,
        type: method,
        data: data,
        success: function(response){
            submit_callback(response, type, target)
        }

    })
}

Callback function:

function submit_callback(response, type, target) {
    switch(type){
        case 'modal':
            console.log(response) //shows that links exists
            console.log(response.links) //logs out as undefined
            post_page(response.links.modal, response.message, target) 
        break;
        case 'target':
            change_target(response, target);
            setUpPageElements();
        break
        case 'page':
            ('body').html(response)
        break;
    }
}

EDIT:

Here is the response after applying JSON.stringify on it:

"{\"message\":\"job successfully created\",\"success\":\"ActionSuccess\",\"data\":{\"attributes\":\"//list of key-values\"},\"type\":\"job\",\"id\":null},\"links\":{\"modal\":\"/client/render/modals/job/success\"}}"

Just to clarify, the attributes exist but are irrelevant to this issue so I have omitted them (they don't actually contain \"//list of key-values\").

Answer №1

Well, it seems the issue wasn't with the front end after all but with the back end; It was for some reason sending the response as text instead of JSON. After tinkering with the code, I managed to resolve the issue, and now it correctly returns JSON data as intended.

A friendly reminder to always double-check that the server is returning the correct data type!

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

Utilize the image button to transfer a picture from your desktop

I have created a table using HTML. The first cell of the table (1,1) contains an image that I want to function as a button. When the image is clicked, I would like to be able to select a photo from my computer and add it to the next available cell in the t ...

Utilizing Vue JS - Creating Async Await function to retrieve data resulting in undefined output

While working in vuejs, I have a helper file containing custom functions that are used throughout the project. Recently, I was refactoring some async await promises, but ran into an issue that I can't seem to resolve. I want to call the fetchUserDat ...

Sometimes Node.js' Express.js fails to send valid JSON

Below is the express code snippet app.post('/v1/sessions' function(req,res){ res.send({id:1234}); }); Unexpectedly, the json response displays as follows: OK{ id: 1234} Questioning the presence of the 'OK' UPDATE Upon reviewin ...

Minimizing switch-case statement into inactive input field (AngularJS)

While the code statement functions as intended, it may not be considered best practice due to the repetition of variables in each case of the switch statement. I am unsure of how to streamline the code or if there is an alternative to using a switch statem ...

Simulating dependencies of Angular 2 components during unit testing

Struggling with accessing mocked service methods in Angular 2 during component unit testing. Seeking guidance on a standard approach, despite following Angular docs closely. The challenge lies in reaching the mocked service's methods. My immediate go ...

Utilize the same variable within a React functional component across multiple components

Within a React functional component, I am utilizing the following constant: const superHeroPowers = [ { name: 'Superman', status: superManPowerList }, { name: 'Batman', status: batmanPowerList }, { name: 'Wonder Woman&a ...

Limit the number of elements in an Angular object by using the filter function

I've implemented an angularjs filter method on a repeated array of items in an attempt to filter numbers using a limitTo filter. However, the result is not reflecting in the DOM. Below is the html code snippet: <div ng-controller="demo as d"> ...

Utilize Vuex to retrieve information using axios by building on existing data that has already been fetched

Utilizing axios in the Vuex store, I am fetching data from an external API that returns an array of objects representing various cities. Each city object includes a zip code, which is essential for retrieving detailed information about the city. My object ...

When rendering, DirectionsRenderer replaces the Marker

I'm currently working on implementing a real-time tracking system for customers to track their deliveries. I have succeeded in setting up markers for the destination and pickup locations, as well as a route path towards them. However, I encountered an ...

The POST method in my Express Node.JS API is malfunctioning, throwing a SyntaxError stating "Unexpected token ' in JSON at position 68" when attempting to parse the data

Struggling to get this post API to function properly, where it's supposed to post data to a database table. However, whenever I test it on Postman, I keep encountering this error: SyntaxError: Unexpected token ' in JSON at position 68 at JSON ...

Implementing a feature that loads older posts on a webpage as users scroll down

Spent hours trying to get my site to automatically load older posts on scroll down with no luck. Any assistance is greatly appreciated :) After researching, [this tutorial][1] seemed like the best solution so I followed it step by step and integrated ever ...

Unable to access the response body of a POST request from an external API within Firebase Cloud Functions

I am encountering an issue with my cloud function in which it makes an http POST request to the LinkedIn API for retrieving an access token. The main problem is that I am unable to retrieve the `body` of the response as it always turns out to be `undefined ...

Is it possible to modify the CSS styling of the file_field?

I am looking to customize the appearance of the file_field in CSS. Rather than displaying the default browse button, I would like to use a simpler upload button for file submission. What steps can I take to modify the CSS of the file_field and replace it ...

"Once the item was returned, its style seemed to have disappeared from

Within an html form, there is a table that can be hidden or displayed based on the selection of a radio button. However, it seems that when the table is hidden and then shown again, one of the style settings is lost. It is desired to maintain the same layo ...

Is npm more similar to Maven or Pip in terms of functionality and usage?

I am curious about the way Javascript's npm handles dependencies in terms of installation. Does it install dependencies on an OS-wide level similar to how Python's pip operates without a virtualenv? Or does npm handle installations more like Java ...

Identify the mouse's location in relation to its parent element, not the entire webpage

A script I've been working on detects the mouse position relative to the page, taking into account a movement threshold of 100px before triggering certain actions. // Keep track of last cursor positions var cursorDistance = 0; var lastCursorX = null; ...

Aggregatable functions for JSON in MySQL

MySQL version 5.7 introduced basic JSON support, but after reviewing the documentation I was unable to locate any JSON aggregate functions. Does MySQL 5.7+ have any JSON aggregate functions available? For instance, if you were to run the query: SELECT i ...

With vuejs, only one place can control the changing of v-model

Hello, I am currently working on integrating VueJS2 code with Laravel Blade. However, I have encountered an issue with the following VueJS2 code: new Vue({ el:'.add_item_to_price_menu', data:{ percentage:null, }, methods: ...

Javascript tabs with clickable links

I have created a page with a series of thumbnails that reveal content below when clicked. The content is positioned absolutely and set to display:none, with javascript changing this for each thumbnail. (I am not very familiar with javascript and learned t ...

Issue with C++ libcurl causing segmentation fault in write callback function

I'm in a rush and looking for a quick solution. I came across another SO question and attempted to apply the code provided there. I am working with a few rest services (not multithreaded) that return json data, but when the CURLOPT_WRITEFUNCTION is tr ...