Sending objects as parameters to a class in JavaScript - an easy guide

Having trouble passing a parameter to the class for handling AJAX errors. The initial function is as follows:

function GetLastChangePass(UserId) {
    var field =
    {
        id: UserId,
 }
    var fieldStringified = JSON.stringify(field)
    $.ajax({
        url: "/Users/LastChangePass",
        method: 'PUT',
        data: fieldStringified,
        contentType: 'application/json; charset=utf-8',
        success: (result) => {
            if (result.includes('12.12.2000')) {
                document.querySelector('#user-tslog').append('')
            } else if (result == 'Not_tslog') {
                document.querySelector('#user-tslog').append('')
            }
            else {
                document.querySelector('#user-tslog').append(result)
            }
        },
        error: (result) => {
            addNewMessage("error", "Error")
            console.error("fail responseText: " + result.responseText)
            console.error("fail contentstatusText : " + result.statusText)
            console.error("fail status  TEST: " + result.status)
        }
    });
}

Created a class that takes the result of the AJAX call like below:

class ErrorConsole {
    constructor(result) {
        this.result = result
 }

    error() {
        console.error("fail responseText: " + this.result.responseText)
        console.error("fail contentstatusText : " + this.result.statusText)
        console.error("fail status : " + this.result.status)
    }
}

The issue arises when trying to pass the parameter using the updated function:

        error: (result) => {
            console.log(result) //===> there is object

            addNewMessage("error", "Error");
            err.error(result) //===> there is indefined

            console.error("fail responseText: " + result.responseText)
            console.error("fail contentstatusText : " + result.statusText)
            console.error("fail status  TEST: " + result.status)
        }

Answer №1

To effectively utilize the ErrorConsole, it is recommended to instantiate it within the constructor rather than inside a function. This approach allows for enhanced access to object attributes:

 error: (result) => {
        console.log(result) //===> there is object
        const err = new ErrorConsole(result) 

        addNewMessage("error", "Error");
        err.error()

        console.error("fail responseText: " + result.responseText)
        console.error("fail contentstatusText : " + result.statusText)
        console.error("fail status  TEST: " + result.status)
    }

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

javascript enables smooth and continuous scrolling

<html> <style type="text/css"> #news { position: relative; box-shadow: 1px 4px 5px #aaa; text-align: left; padding: 5px; line-height: 20px; height: 235px; background: white; border: 1px solid #ccc; border-radius: 15px; background: #eee; wi ...

A guide on displaying complete text as the container width expands using Tailwind CSS and Next.js

On my platform, users have the ability to create albums and give them names of any length. When a user creates an album, it generates a div along with a link (the album's name) and two icons. I am looking to implement a feature where if a user enters ...

ReactJS import duplication problem arising from utilizing npm link for component testing prior to npm package release

I have a basic component structured like this. import React, {useState} from 'react'; function MyComponentWithState(props) { const [value, setValue] = useState(0); return ( <p>My value is: {value}</p> ) } expo ...

The calendar fails to display events once the $scope.splice(0) and $scope.push(event) functions are executed

Greetings, I am encountering an issue with the angular ui-calendar (angular wrapper for arshaw's fullcalendar). Initially, I load the events using a $http call in the first step and the calendar displays correctly. However, in the next step, when lo ...

What is the reason behind router.base not functioning properly for static sources while running 'npm run build' in Nuxt.js?

Customizing Nuxt Configuration const BASE_PATH = `/${process.env.CATEGORY.toLowerCase()}/`; export default { router : { base : BASE_PATH }, } In addition, there is a static source for an image in the component: <img src="/mockups/macbookpro_01. ...

Is there a way to retrieve the width of the parent element in ReactJS from a child component?

The issue has been fixed: I forgot to include .current in my ref... I am trying to determine the width of the element that will hold my component. I came across a solution on SO, but unfortunately it did not work for me as it returned undefined: import R ...

Troubleshooting AngularJS: Diagnosing Issues with My Watch Functionality

I need to set up a watch on a variable in order to trigger a rest service call whenever its value changes and update the count. Below is the code snippet I have: function myController($scope, $http) { $scope.abc = abcValueFromOutsideOfMyController; ...

What is the process for exporting a class and declaring middleware in TypeScript?

After creating the user class where only the get method is defined, I encountered an issue when using it in middleware. There were no errors during the call to the class, but upon running the code, a "server not found" message appeared. Surprisingly, delet ...

Generating a JSON file using JavaScript amidst the presence of unconventional characters in JSON keys

In my Node Red Function Node, I'm currently facing a challenge of generating a JSON file from JavaScript code. The specific format I need for the JSON file is as follows: [ { "H-Nr.":"1", "Pos.-Nr.":"1" }, { "H-Nr.":"1", ...

Is it possible to send an array containing multiple JSON objects to PHP through a POST

After numerous attempts, I'm still encountering the same error. Here is the Json String that's causing the issue: [{"cart":{"itemid":"2","itemAmount":"2"}},{"cart":{"itemid":"3","itemAmount":"1"}}] I attempt to pass it to PHP using this cod ...

Delete particular user inputs following a $.ajax request

I have created a search feature with inputs that allow users to search the database using ajax requests. Unfortunately, I am facing an issue where the response from the server includes the search inputs themselves. This is not what I want. Here's a ...

Utilizing JSX within this.state results in it being displayed as plain text when rendered

Currently, I am dynamically rendering a list of elements and I need to insert other elements in front of them based on key-value pairs. I want to utilize <sup></sup> tags for these elements, but they are appearing as plain text rather than sup ...

When implementing ReplaySubject in Angular for a PUT request, the issue of data loss arises

I seem to be encountering a problem with the ReplaySubject. I can't quite pinpoint what I've done wrong, but the issue is that whenever I make a change and save it in the backend, the ReplaySubject fetches new data but fails to display it on the ...

Encoding a string in JSON that contains the "#" symbol along with other special characters

The client side javascript code I have is as follows: <html> <script type="text/javascript" src="js/jquery.min.js"></script> <script> $(document).ready(function() { //var parameters = "a=" + JSON.stringify( ...

Merge two JavaScript functions

I've been attempting to merge two if functions together but I keep encountering errors. Despite trying different methods, I have not been successful in combining them. My goal is to check if the body has a specific class and if it does, I want to unc ...

What is the reason behind combining all states into a single location in Redux, even if they are not globally accessible?

As a newcomer to React and Redux, I have found them to be quite enjoyable when used together in a small sandbox application. However, as I consider larger applications, I can't help but question why Redux stores the entire application state in a singl ...

"Encountering a strange issue where submitting a form with Jquery and AJAX in Rails does not work as expected, causing the index

Currently facing a unique issue with a jQuery/Ajax HTML update form. The application in question is a single-page TODO App that utilizes a Rails controller, where all changes to the DOM are made through jQuery/Ajax. After rendering the TODOs on the page v ...

Exploring the method of extracting data from PHP arrays through AJAX

Currently, I am using an ajax call to retrieve data from a PHP page. This PHP script is responsible for querying the database between two specified dates. Here is the snippet of PHP code: if(isset($_POST['fromdate'])){ $fromdate = $_P ...

Tips for maintaining the functionality of IFrame?

I am encountering an issue with tracking clicks on a div that contains an IFrame. While the tracking functionality works, it seems to interfere with the IFrame's functionality. Is there a way to resolve this and make both functionalities work simultan ...

The issue of transform scale not functioning properly in conjunction with background clip and gradients in CSS

Looking to transform a div with the transform: scale(-1,1) property while using background-clip: text on the text within it. However, this causes the text to disappear. Here's what I've attempted: .reverse { transform: scale(-1, 1); } .gr ...