The method hasOwnProperty does not function as intended

Upon receiving a JSON object from the server ({error:true}), I attempted to verify if the key "error" exists. Surprisingly, the function hasOwnProperty returned false.

Here is the snippet of code that led to this unexpected result:

$http({
        headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' },
        url: '/Modules/Partners/Mailing/SendMail.ashx',
        data: $.param({ contact: JSON.stringify(contact), body: partnerObject.mailTemplate.longValue, title: "" }),
        method: 'POST'
    })
    .success(function (data, status, headers, config) {
        console.log(data);
        console.log(data.hasOwnProperty('error'));

       if (data.hasOwnProperty('error')) {
           deferred.reject(contact);
       } else {
           deferred.resolve(contact);
       }
       //console.log(data)

    })
    .error(function (data, status, headers, config) {
        deferred.reject(contact);
    });

Despite observing the presence of the "error" key in the object through the console output, the hasOwnProperty('error') check yielded false.

https://i.sstatic.net/rJwJ7.png

Answer №1

I believe the issue lies with the JSON object you are receiving. The key is actually not error, but rather 'error'. You can try checking if data.hasOwnProperty("'error'") would be effective.

Answer №2

To determine if a property exists on an object or array, you can utilize the in operator. For example, the statement "error" in data will evaluate to true.

Answer №3

Your successful function is designed to handle data in the form of a String, not as JSON:

.successful(function (data, status, headers, configuration) {
    var outcome = angular.fromJson(data);

    if (outcome.hasOwnProperty('failure')) {
        deferred.reject(contact);
    } else {
        deferred.resolve(contact);
    }
    //console.log(data)
})

By the way: If it were JSON format being processed, you would observe the following in the console:

https://i.sstatic.net/NaKyI.png

Answer №4

Have you attempted utilizing if(data && data.error) rather than

if (data.hasOwnProperty('error'))

The issue is likely due to the error property being inherited. Learn more about hasOwnProperty and inherited properties by visiting this page

Answer №5

To ensure proper conversion of data received from the server, first check the content-type to be 'application/json'. If it is, the data will be implicitly converted into a JavaScript object. You can verify this by using "typeof data" - it should return as "object". If the data is returned as a string instead, you will need to parse it into an object using JSON.parse.

Answer №6

Can someone explain why the object is being returned like this: JsonSerializer.Serialize("{\"error\":true}");

Instead of JsonSerializer.Serialize("{'error':true}"); or JsonSerializer.Serialize("{error:true}");

I need help resolving this issue

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 retrieve the Axios response using Express?

I've recently delved into working with Express and I'm currently struggling with making an Axios request using route parameters, and then updating some local variables based on the response. Here's a snippet of what I've been working on ...

What is the best method for extracting html-string from html-string across different browsers?

Works perfectly in Chrome and FF, but encountering issues with Safari. var content = '<div><span><p>Can you catch me?</p></span></div>'; content = $.parseXML(content); var span = $(content).find('span&apo ...

Using AngularJS ng-repeat with jQuery find yields a single element result

I'm in the process of developing my very first AngularJS application, and I've run into an issue with the jQuery find function. Essentially, what I'm attempting to do is utilize a custom HTML component that contains a list of buttons generat ...

Streamline event listeners with a pair of attributes

I am working with a function that requires one parameter: function magical(element){ ... } In my project, I have multiple click handlers attached to different elements and classes that are invoking this function: $('#div1').click(function(){ ...

Using AJAX to communicate with a MySQL database and create a countdown timer using JavaScript

I have been trying to display data from a database using Ajax and incorporate countdown timers with times also fetched from the same database. It has been a struggle for me for almost 24 hours now. You can check out the main code here where you will notic ...

Tips on removing the red border from a text box within an HTML form with the help of AngularJS

My form has the following appearance: https://i.stack.imgur.com/T3NQW.png Upon clicking the submit button, the textbox fields display a red border due to the required attribute. Afterwards, I aim to click the reset button in order to remove the red bord ...

Parsing form array/bracket fields into actual arrays with ExpressJS

Is there any middleware available or code snippets that can help me to convert form fields with square brackets (e.g. 'contact[21][name]') into actual arrays for ExpressJS 3? I am looking for something like this: for(key in req.body){ if(ke ...

Top tips for effectively crafting and interpreting an app configuration file in an Angular application

My Angular application needs to be installed on multiple sites, with each site requiring different configurations such as colors, texts, logos, and backend servers. I would like to create a configuration file that can be easily modified and read by the Ang ...

Changing the HTML Structure of the md-datepicker Component

I am currently utilizing the md-datepicker component on my webpage. I have a specific need to include a CSS class to the produced input element. Is there a method to alter the markup that is generated by md-datepicker? <md-content> & ...

Error in Origin Access Control detected in the XMLHttpRequest

We encountered the following error when using the REST API: "No 'Access-Control-Allow-Origin' header is present on the requested resource." Here is my code snippet: function get_XmlHttp() { var xmlHttp = null; if(window.XMLHttpRequest ...

What is preventing me from using Selenium/Javascript to control Firefox on Ubuntu 22.04, when I am able to do so with Python?

My python script effectively controls Firefox using Selenium: from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Firefox() driver.get("https://dev.to") driver.find_element(By.CLASS_NAME, "crayons ...

Dealing with errors when implementing an Angular 2 route guard that returns an Observable of type boolean can be a

My route guard is implemented as follows: @Injectable() export class AuthGuard implements CanActivate { constructor(private router: Router, private authenticationSvc: AuthenticationService) { } canActivate(): Observable<boolean> { return this. ...

Can anyone provide a way to sort through a list of dictionaries in Ansible and identify all lists that contain a certain key value or values?

My goal is to retrieve the lists where a key ('minio_vf') has a specific value (True) from the input data. To achieve this, I have utilized the selectattr('minio_vf', '==', True) filter. Input Data #1 (contains 'minio_vf ...

Retrieving complete credit card information with the help of JavaScript

I've been grappling with extracting credit card data from a Desko Keyboard, and while I managed to do so, the challenge lies in the fact that each time I swipe, the card data comes in a different pattern. Here is my JavaScript code: var fs = require ...

How can we integrate information from a local JSON file onto our website?

My role is with a small publishing company that has an internal website featuring a static HTML table showcasing our published products. We are looking to dynamically list and sort our products (with about 1-2 items published daily) based on data from an ...

Filtered Owl Carousel

Hello everyone. Just wanted to mention that our English may not be perfect. I managed to filter with owl carousel by tweaking some codes I found online. It's working now, but I'd love for it to have an animated effect while filtering, like a fad ...

Expanding DIV Box with jQuery

Have you ever come across those cool jQuery Expandable box features that expand to reveal a larger image in the center of the screen when you click on a Thumbnail image? But what if I want to achieve something similar, where instead of just an image insid ...

What is the correct way to align text in jsPDF?

I'm currently encountering an issue with the jsPDF library. Although PDF generation works fine, I am struggling to justify text properly. The align: 'justify' attribute seems to function the same as align: 'left', and setting a spe ...

Refresh the information displayed in the HTML table

I've been assigned the task of developing a shift management web app to help our current employees track their shifts. The website StaffHub has been suggested as a reference for my web app, and I am currently focused on implementing the calendar featu ...

Leveraging the html-webpack-plugin for creating an index.html file within Webpack (specifically in a project based on the vue-simple boiler

For every build in Webpack, I am attempting to create a customized index.html file. In order to achieve this, I have incorporated html-webpack-plugin. I comprehend that to generate an index.html file within my dist directory, the following configurations ...