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

Issue encountered when attempting to send quotation marks to the web service using AJAX

Using .ajax, I am sending data with the following attributes: data: '{ "UserInput" : "' + $('#txtInput').val() + '","Options" : { "Foo1":' + bar1 + ', "Foo2":' + Bar2 + ', "Flags":"' + flags + '", "Im ...

Using percentages to position Div elements

Currently, I am working on an HTML page that requires a div element spanning the full width of the page. My goal is to arrange other divs within this full-width div using percentages rather than pixels. The class associated with this div is .question. Thi ...

Loop through a JSON object using a sequence of setTimeout() functions

After running another function, I have retrieved a JSON object stored in the variable 'json_result'. My objective is to log each individual JSON part (e.g. json_result[i]) after waiting for 5 seconds. Here was my initial attempt: for (let key ...

What is the best way to implement a required input field in Vue.js?

I need some assistance with my chat functionality. I want to prevent users from sending empty messages, so I want to make the input field required. Can you please help me with this? I have already tried adding "required='required'" to the input ...

Utilizing Ajax in PHP to Upload Files

I'm encountering an issue while attempting to upload a file and send it via AJAX. The error message I am receiving is as follows: Notice: Undefined index: xlsFile in Here is the code snippet: HTML FORM : (this form is within a Modal Popup) <f ...

Is there a way to store div content in a PHP Session?

Just starting to learn php & ajax, so be patient with me. I have a clickable map. When the user clicks on a point, the value is displayed in a div. Once they select a point, they should be able to proceed to the next step. Now I want to save the content ...

"Encountering an Error with Route.get() when attempting to utilize an imported

I have a function that I exported in index.js and I want to use it in test.js. However, when I try to run node test, I encounter the following error message: Error: Route.get() requires a callback function but got a [object Undefined] What am I doing wro ...

submitting a collection of hashes to a server using jQuery

I'm facing an issue with sending data to the server. I have an array structured like this: places = new Array(); places.push({name: "ci", loc: "bo"}) places.push({name: "ae", loc: "ea"}) if I try to send this data to the server using the following J ...

What is the process for removing an added message using jQuery after it has been appended by clicking the same button?

https://i.stack.imgur.com/YsmKZ.pnghttps://i.stack.imgur.com/dW2lo.pngI have searched extensively through previously asked questions without success. My goal is to remove the previous appended message when the submit button is clicked again. This functiona ...

While developing an exam portal with Angular and Spring Boot, I encountered an issue when trying to incorporate a name field as [name]

Component.html <div class="bootstrap-wrapper" *ngIf="!isSubmit"> <div class="container-fluid"> <div class="row"> <div class="col-md-2"> <!- ...

The function passed to the modal is not functioning correctly when stored within the state

Is it possible to create a unique modal that can be utilized for multiple actions on the same page? To achieve this, I have implemented a state to store the title, description, and submit function for modal click and modal open state. In addition, I want t ...

Error: JavaScript alert box malfunctioning

I am facing an issue with my JavaScript code. I have successfully implemented all the functionalities and can change the color of an image background. However, I am struggling to prompt a pop-up message when clicking on an image using "onclick". I have tri ...

What is the reason for the inconsistency in CORS post requests working for one scenario but not the other?

Currently, I am facing an issue while attempting to add email addresses to a mailchimp account and simultaneously performing other tasks using JavaScript once the email is captured. Here's the snippet of my JavaScript code: function addEmail(){ v ...

Incorporate an Ajax response script with a Django HttpResponse

How can I pass the ajax response obtained from the view to the template using HttpResponse? I'm unsure of the process. view.py analyzer = SentimentIntensityAnalyzer() def index(request): return render(request, "gui/index.html") @csrf_exempt d ...

Transferring a JavaScript variable to JSP using AJAX

I'm struggling to figure out the correct syntax to pass a JavaScript variable named "textVal" to a jsp file. Here is my code snippet: function show(textVal){ AJAX.onreadystatechange = handler; AJAX.open("POST","service.jsp",true); AJAX.setR ...

What are the steps for retrieving data on the server side by utilizing a token stored in localStorage?

Currently, I am diving into the official documentation for Next.js and utilizing the App router. On the data fetching patterns page, it explicitly states: Whenever possible, we recommend fetching data on the server To adhere to this recommendation, I cr ...

Malfunctioning string error in Django view caused by boolean inconsistencies

Looking to extract variables from a post request made by Javascript. Upon inspecting the received variables in my view, I found the following: >>> print request.body {"p":"testprd","cash":false,"cheque":true,"debit":false,"credit":true} The valu ...

Parsing the JSON string from PHP using JSON.parse resulted in an unexpected and strange array

I've encountered a challenge when trying to transfer a JSON object from the server to client-side JavaScript. I fetched rows of data from a MySQL query and stored them in $result. Below is the code snippet: var json = '<?= json_encode($resu ...

jQuery does not trigger background image change in Webkit

const displayPreviewImage = (imageUrl) => { $('#slideshow-container').css("background-image", `url('files/images/store/content/templates/websites/preview_images/${imageUrl}'`); } I have a function here th ...

When using AngularJS, fetching image data with $http.get may result in special characters being displayed

Currently, I am utilizing a private API with PHP and the slim framework. However, when I try to access a route that provides image data, the response appears to be abnormal (possibly due to a charset issue). The server is sending the image using the readf ...