javascript unusual comparison between strings

I am working on an ajax function that is responsible for sending emails and receiving responses from the server in a JSON format with type being either success or error.

$("#submit_btn").click(function(event) { 
    event.preventDefault();

    var post_data = {
        'email': $("#email").val()
    };
    $.post( "sendEmail.php", post_data ).done(function(response){
        if(response.type == 'success'){
            $("#sentmail").fadeIn("slow")
            setTimeout(function(){
                $("#mail").val("Enter your email here");

                $("#sentmail").fadeOut("slow")  
            },3000);
        }
        else{
            $("#sentmailfail").fadeIn("slow")
            setTimeout(function(){
                $("#mail").val("Enter your email here");

                $("#sentmailfail").fadeOut("slow")  
            },3000);
        }
    },"json")
});

What I find intriguing is when I console.log(response), it shows something like

{"type":"success","desc":"something"}
. However, immediately after that,
console.log( (response.type == "error") ) // TRUE
.

If I store the console logged response into a variable, say

a = {"type":"success","desc":"something"}
, then a.type == "error" evaluates to false.

Could someone shed some light on this peculiar behavior?

Answer №1

If you see the output of console.log(response) as

{"type":"success","desc":"something"}

then it is likely that response is still in string format (containing JSON) and strings do not have a type property:

> "foo".type == "error" // `undefined` is never equal to a string
false

Objects appear differently in the console usually:

> console.log({"type":"success","desc":"something"})
Object {type: "success", desc: "something"} // at least in Chrome and Firefox

Tip: Make sure to parse the string first:

response = JSON.parse(response);

Regarding jQuery:

I noticed that your intention is to let jQuery handle the JSON parsing, but you are passing "json" to the wrong function. It should be passed to $.post(...), not to .done(...):

$.post("sendEmail.php", post_data, "json").done(...);
// instead of 
// $.post("sendEmail.php", post_data).done(..., "json");

This way, manual parsing is not required.


Related: How to Parse JSON in JavaScript?

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 can be done to resolve the slowdown caused by an Ajax request within the function?

I've implemented drag and drop functionality for saving images, but I'm facing an issue with getting an instant preview of the saved images. Whenever I try to send the image to the server using an ajax request, the image doesn't appear on th ...

"Time" for creating a date with just the year or the month and year

I am trying to convert a date string from the format "YYYYMMDD" to a different format using moment.js. Here is the code snippet I am using: import moment from 'moment'; getDateStr(date: string, format){ return moment(date, 'YYYYMMDD&a ...

refresh PHP automatically using JavaScript

Working on my Laravel application, there is a JavaScript function that I have defined: function abc(){ var x = '<?php ($user && ($user->first_name == "" || $user->number == "")) ?>'; } Upon initial page load, the variable ...

Transferring a Query between Domains with the Help of JavaScript

It is necessary to develop a function that generates a query based on the user's input of "Test" in an INPUT on Site A (SiteA.com) and then redirects to Site B within the same window, passing along the query (SiteB.com/search.aspx?k=test). Code snipp ...

Identifying the Origin of the Mouse Pointer When Hovering Over Elements

Could someone please advise on how to detect the movement of the mouse pointer using jQuery when it hovers over an element such as a div? I am looking for a way to determine if the mouse pointer entered the element from the top, left, bottom, or right sid ...

Incorporate Vue into a template using variables and props

Currently in the process of building a vue app and wondering how I can seamlessly integrate it into a template while passing variables (props) into it. When I execute npm run dev, the app and all its components are coded with no issues. After running npm ...

Disable the sorting feature on selected columns

I have a Datatable in JS with a scroll bar that I added using scrollY. However, it is displaying unnecessary small arrows within the table which I do not want. I have tried various methods to remove them but without success. Can someone please help me wi ...

Trying out the effectiveness of Ajax for email validation on a Rails platform

I am having trouble setting up jquery-rails in my Rails application to check if an email exists in the database. When I try to implement it, nothing happens as expected. Here is a snippet of my code: <%= form_for @user, :html => {:class => "col-m ...

Hiding icons in a jquery datatable's table

I am currently developing an inline editing feature, and I would like to display a green checkmark in a column cell to indicate that the record has been updated. However, I need to hide it initially. This is how it looks at the moment: As shown, the chec ...

Child element casting shadow over parent element

I am currently using box shadow for both the parent (.map) and child (.toggle-button): .map { position: fixed; top: 20px; right: 0; width: 280px; height: 280px; z-index: 9999; box-shadow: 0px 1px 6px 0px rgba(0,0,0,0.3); } .map ...

What is the process of including data in Vue using refs?

My goal is to click a button and have the page scroll up or down. However, I need references for each span I add in order to include an index. The issue arises when trying to incorporate this index into the method. How can I add data to these references? ...

Tips for Sending an Ajax POST Request

I've been using the following code snippet to initiate a POST request to my node API in order to generate a PDF. However, upon execution, my node console displays the following errors: $('#renderPDF').click(function(){ var request = $ ...

Utilizing Socket IO and Node JS to stream audio from a microphone via sockets

I am currently developing an app that requires users to use their phone's microphone to communicate with each other in the game lobby. However, I have encountered several challenges along the way. My approach involves using Node JS socket io and sock ...

Using JavaScript build-in functions in a Vue template allows for enhanced functionality and

Is there a way to utilize JavaScript built-in functions within a Vue template? {{ eval(item.value.substring(2)) }} I attempted to use the JS function eval() in {{}}, but encountered several errors such as: [Vue warn]: Property or method "eval" i ...

The Webix component is experiencing a lack of refreshment

function refresh_group_items(){ //console.log("calling1"); window.setTimeout(function(){ $$("cfg").reconstruct() }, 3000); } $.ajax({ type: "POST", xhrFields:{ withCredentials: true }, beforeSend: function(reque ...

Ajax request received no data from API

I have been facing an issue with my code where I am posting an email on an API URL using an HTML form and PHP code with an Ajax call. However, the response I am getting is empty. I need to display this response on the same page below the form. I am sharing ...

How can I incorporate arithmetic operators within a function in EJS?

Currently, I am developing an express app that includes a booking form using ejs with added functionality for payment processing. In the code, I have a select tag where the selected text is stored in a variable. Although console logging shows the value co ...

A guide on showcasing real-time data with Angular's service feature

home.component.ts <h1>{{ (reportsToday$ | async)}}</h1> <div echarts [options]="alertsDaily$ | async"> <div echarts [options]="alertsToday$ | async"> <div [onDisplay]="alertsDaily$ | async"> report.component.ts constructor( ...

Developing a dynamic slideshow using jQuery

I'm working on a website where I want an image to change when I click on a specific piece of text. Currently, I have set up a class called "device" with one of them having the class "active" like this: <div class="col-md-3"> <div c ...

Grails - fetching data upon page load and retrieving via ajax request

On page load, I have an ajax call that needs to be made to an external API in order to download json data. Due to compatibility issues with IE8, I cannot directly call the API from the page itself, so I am using a proxy through Grails to bypass origin prob ...