Modifying JavaScript Objects

After referring to the discussion at , I encountered a challenge with my javascript ajax function that retrieves JSON data. My goal is to trigger different js events based on the key-value pairs of the JSON response, but unfortunately, I am facing difficulties accessing the JSON by key directly. As an alternative, I converted the JSON into a JavaScript object and attempted to use conditional statements (IF), only to find that it's not functioning as expected. Despite receiving a successful response in the JSON, I keep encountering error windows. Given my limited experience in JavaScript, I seek guidance and advice on how to resolve this issue.

success: function (data) {

    var json = data,
        obj = JSON.parse(json);


    if (obj.hasOwnProperty('success')) //if data = {"result":"success"}
    {
        $('div#loginResult').text("Login result: " + obj.result);
        $('div#loginResult').addClass("error");
    } else // /if data = {"result":"error"}
    {
        $('form#loginForm').hide();
        $('div#loginResult').text("Login result: " + obj.result);
        $('div#loginResult').addClass("success");

    }
}

Answer №1

It seems like there may be an error in your code. Instead of checking for a property 'success', you should check the value of the property. Here's a suggestion:

success: function (data) {

        var json = data,
            obj = JSON.parse(json);


        if (obj.result === 'success') //assuming data = {"result":"success"}
        {
            $('div#loginResult').text("Login result: " + obj.result);
            $('div#loginResult').addClass("error");
        } else //assuming data = {"result":"error"}
        {
            $('form#loginForm').hide();
            $('div#loginResult').text("Login result: " + obj.result);
            $('div#loginResult').addClass("success");

        }
    }

https://jsfiddle.net/ghkokgg7/

Answer №2

  success: function (response) {

                var jsonData = response,
                    jsonObject = JSON.parse(jsonData);

                if (jsonObject.outcome === 'failure') //if response = {"outcome":"success"}
                {
                    $('div#loginResult').text("Login outcome: " + jsonObject.outcome);
                    $('div#loginResult').addClass("failure");
                } else // /if response = {"outcome":"failure"}
                {
                    $('form#loginForm').hide();
                    $('div#loginResult').text("Login outcome: " + jsonObject.outcome);
                    $('div#loginResult').addClass("success");

                }
            }

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 link a list of strings to an 8-character key?

On my WPF form, I have a ComboBox and a TextBox. The ComboBox contains options related to email addresses that the user will enter into the TextBox. I want each option in the ComboBox to be associated with an 8-character key, which will then be serialized ...

Difficulties with managing button events in a Vue project

Just getting started with Vue and I'm trying to set up a simple callback function for button clicks. The callback is working, but the name of the button that was clicked keeps showing as "undefined." Here's my HTML code: <button class="w ...

How is the height or width of the Bootstrap modal determined?

I'm having trouble utilizing Jschr's modified Bootstrap-Modal for different modal sizes. I can't seem to understand why some modals appear taller, wider, or have other specific dimensions. For more information, refer to the documentation: ...

Retrieving an Array in CakePHP Through an Ajax Post Request

Despite the countless other 'duplicate' questions on this topic, I still find myself stuck. My goal is simply to log an array passed from PHP via ajax. In CakePHP 2.X: In View: <button class="quarter q1" value="1" value>Quarter 1</but ...

pdfMake introduces a page breaking effect when the canvas is utilized with the type "line"

Can anyone shed some light on why a canvas declaration with the type "line" is causing a page break in the generated PDF? I've tried removing all canvases and the page break disappears, but I can't identify the root cause. Any insights would be ...

Attempting to access an HTTP Node server from within an HTTPS environment resulted in an SSL error

I am faced with the challenge of connecting to a socket.io from a React client within a Node server. Both the React client and the location of the Node server (a microservice housed in a separate Docker container alongside a Java container) are operating o ...

Merge JavaScript files from various folders using grunt's configuration settings

I am currently working with Grunt and Sass, and I am in search of a SASS-like feature that will allow me to import any JavaScript file I desire and merge them into a single file based on some configuration depending on the directory I am in. For instance, ...

Vue.js - Resetting child components upon array re-indexing

I am working with an array of objects const array = [ { id: uniqueId, childs: [ { id: uniqueId } ] }, { id: uniqueId, childs: [ { id: uniqueId } ] }, ] and I have a looping structure ...

Is there a simple method to add animation to a group of images displayed on click using JQuery?

Here is my JavaScript code that I'm currently using: $(document).ready(function() { $(".button-list .next").click(function() { project = $(this).parents().filter(".projektweb").eq(0); currentimg = project.find(".im ...

Checking CORS permissions with a pre-flight OPTIONS request

During development, I implement a middleware called cors using the following syntax: app.use(cors({origin: 'http://localhost:8100'})); However, I have noticed that for every route request, two requests are being made as shown in the image below ...

PHP File Upload with AJAX and JSON Integration for Form Submission

Here is a code snippet that demonstrates how to read data from a form, save files in a folder, and write the information to a JSON file: Javascript: var name = $("#name").val(); var image = $("#image")[0].files[0]; var model = $("#model")[0].files[0]; v ...

I possess an array with a specific structure that I wish to substitute the keys as demonstrated below

The data array is currently structured in this way. I have attempted various methods but have not been able to find a suitable solution. I need to send the JSON below via an AJAX request, however, I do not want the keys 0 and 1 in both child arrays. [sch ...

The most efficient way to invoke a jws void method in the fewest steps possible

When calling a void method of a SOAP JWS web-service using JavaScript without expecting a result back, what is the most efficient and concise approach? ...

Manipulating the DOM with Javascript and jQuery: Adding a new element and retrieving its reference

I am encountering an issue with a Web App that relies on JavaScript and jQuery. Essentially, the website includes a button that triggers a JavaScript function when clicked. Within this function, there are two other functions named Foo and Bar. Foo generate ...

Is the security of Angular's REST authentication reliable?

My goal is to establish a secure connection with a REST service using Angular. I have come across the official method, which involves setting the authentication ticket like this: $httpProvider.defaults.headers.common['Authorization'] = 'dhf ...

The style properties of Material UI ButtonGroup are not being properly applied

https://i.sstatic.net/apxUH.gif Within a Grid container, I have a Product image with associated buttons. The visibility of these buttons is determined by specific state variables. If the product quantity is 0, an "ADD TO CART" button is displayed; otherwi ...

Change the color of the plotly button when it is clicked

I recently implemented a custom button on my plotly modeBar and I would like it to retain a distinct color when clicked. This would help visually indicate its "active" state, allowing users to easily discern whether it is enabled or disabled based on its ...

When verifying the existence of a Json attribute, the conditional statement will exclude the `if

In my Python3 script, I have a function to determine if an attribute exists in a JSON object and has a value other than null: def check_attribute(data, attribute): return (attribute in data) and (data[attribute] is not None) This function checks whet ...

Can Angular components be used to replace a segment of a string?

Looking to integrate a tag system in Angular similar to Instagram or Twitter. Unsure of the correct approach for this task. Consider a string like: Hello #xyz how are you doing?. I aim to replace #xyz with <tag-component [input]="xyz">&l ...

Using JSON for saving HTML code

Currently delving into the world of AngularJS and thrilled about organizing data in JSON format. I have decided to create a practical application for hands-on learning. The app is an online magazine where I store the essential data for each article in art ...