The conditional statement is failing to execute properly in the JavaScript AJAX response

When checking the value in the alert, it always shows as 'Initial'. However, the condition if(checkoption == 'Initial') always returns false. The actual code is as follows:

function changeItem(id,item,option) {

    var xhttp; 
    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
            if(this.responseText=="Initial"){
            $("#Initial").load("Item-<%=cha_id%>.html #Initial", function()
            {
                document.getElementById("Initial").style.display = 'block';
                document.getElementById("Final").style.display = 'none';
            });
        }
        if(this.responseText=="Final"){
            $("#Final").load("Item-<%=cha_id%>.html #Final", function()
            {
                document.getElementById("Initial").style.display = 'none';
                document.getElementById("Final").style.display = 'block';
            }); 
        } 
    }
    };
    xhttp.open("GET", "<%=landingpage_basepath %>/ChangeItemValue111?info="+id+"&item="+item+"&option="+option, true);
    xhttp.send();
    }
}

Answer №1

Check out the modified code snippet below.

 xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
      var responseText = this.responseText;

      alert(responseText);

      if(responseText == 'Initial') {  
         alert(this.responseText);  
      }
      else if(responseText == "Final"){  
         alert(this.responseText);  
      }
      else {  
         alert("Hello"); 
      }
   }
};

xhttp.open("GET", "<%=landingpage_basepath %>/ChangeItemValue111?info="+id+"&item="+item+"&option="+option, true);
xhttp.send();

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

Identify the moment when the SPAN element reappears in sight

I have a question that may have been asked before, but I haven't found a satisfactory answer yet. Within my HTML code, I have a SPAN element with an onclick event, like so: <span onclick='loadDiv()'>Text</span> When a user cli ...

Utilize JavaScript to seamlessly play a Spotify track within the Spotify client without disrupting your current

A little while back, I recall the simplicity of clicking play on a song within a website and having it instantly start playing on my computer without any additional steps. It was seamless and effortless. My goal for my website is to have music start playi ...

Encountering module resolution issue following npm-link for the shared component repository

Attempting npm-link for the first time to establish a shared component repository, and encountering an issue. The project seems to be linked correctly based on this message: /Users/tom.allen/Development/main/project/node_modules/@linked/project -> /usr ...

Passing data from child to parent in Angular using EventEmitter

I have integrated a child grid component into my Angular application's parent component, and I am facing an issue with emitting data from the child to the parent. Despite using event emitter to transmit the value to the parent, the variable containing ...

Accessing the ApiView endpoint using an Ajax request resulted in a forbidden HTTP error

I've been attempting to make an AJAX Request to an ApiView endpoint. $.ajax({ url: '{% url 'edit_custom_user_additional_info' %}', method: "patch", data: $form.serialize(), ...

What are some ways to optimize the efficiency of handling a sizable JSON object in React Native?

I am currently developing an application using React Native and have encountered significant slowdowns during transitions when loading more data. I am exploring alternative app structuring methods to prevent these performance issues, especially as the JSON ...

What is the best way to submit a form using ajax in PHP?

I'm experiencing an issue with my ajax form submission. I have set up a jquery alert to display when the submission is successful, but it is not showing up. I suspect that the submission is unsuccessful. Can anyone help me figure out why? Here is the ...

Creating a dynamic JSON object with repeated keys: A step-by-step guide

My current predicament seems quite challenging as my supervisor has mandated that I send a JSON over an AJAX post call using jQuery with duplicate keys. Struggling to achieve this task, I found that if I were to structure the JSON like so: $.post("someurl ...

Rendering issue with component

I am encountered with a situation where one component is failing to render its sub-component. Surprisingly, there are no visible errors in the console. The data I'm expecting from the web call is also coming through without any issues. However, for so ...

The Quickest Way to Retrieve Attribute Values in JavaScript

I'm trying to access a specific attribute called "data-price". Any tips on how I can retrieve the value of this attribute using this syntax: Preferred Syntax div[0].id: 48ms // appears to be the quickest method Alternative Syntax - Less Efficient ...

Error: Unable to execute fields.map function while generating a dynamic sitemap using next-sitemap module

I'm in the process of creating a dynamic sitemap for my website and here's the code I'm using: import { GetServerSideProps } from 'next'; import { getServerSideSitemap, ISitemapField } from 'next-sitemap'; import { makeSl ...

Event that occurs when modifying a user's Firebase Authentication details

Monitoring User Actions with Firebase Authentication Within my application built using Angular, Node.js, and Firebase, I am seeking a method to track user events such as additions, modifications, and deletions. Is there a mechanism to recognize when a us ...

What is the process for indicating the cache directory in npm5 when using the install command?

When using yarn, you can specify the cache folder with yarn --cache-folder [CACHE_FOLDER]. Is there an npm5 alternative to this? One option is to set the cache folder with a separate command: npm config set cache [CACHE_FOLDER]. However, I'm wonderin ...

Use React to insert a leading zero next to a number in the input field if the number is greater than 10

I have scoured the web and consulted resources like this one but haven't found a solution that addresses my specific issue with adding padding to input numbers. My goal is to automatically add a leading zero whenever the number inside an input field i ...

Capture individual frames from angular video footage

Trying to extract frames from a video using Angular has been quite challenging for me. While browsing through Stack Overflow, I came across this helpful post here. I attempted to implement the first solution suggested in the post, but unfortunately, I was ...

Challenge encountered while using the like operator with Integer data type in Mongoose

I am encountering an issue with constructing a where query in Mongoose for an integer data type. The key 'facevalue' is of integer data type. When I execute a find query, it appears something like this: Below is the code snippet: var orCond ...

Will my variables become unbound when a new object is created?

Currently, I am developing a component within my Angular application where I am binding an object: CustomComponent.js angular.module("app").component( "customComponent", { controller: function() { var ctrl = this; ctrl.createInstance ...

Verify if the user possesses legitimate Jira REST API credentials

I am currently using the npm module jira-client to send API requests to my Jira system. I need a way to verify whether the user has valid credentials before proceeding. Depending on the validation result, I plan to either: Inform the user that their use ...

Transfer your documents effortlessly as soon as they are

I am having trouble implementing an automatic file upload feature without the need for a separate upload button. Below is the code I have so far, excluding the irrelevant CSS. //html <!-- some codes here--> <input type="file" id="f ...

An effective method for transferring form input and music between pages utilizing JavaScript

I've been grappling with this issue for quite some time now. On the initial page, I have a form like this: <form id="user" name="user" method="GET" action="the-tell-tale-heart.html"> Name: <input type="text" name="name"> & ...