Comparing "if" and "else" within the XMLHttpRequest() function will not

function banUser() {
  var userToBan = document.getElementById('userToBan').value;
  var cid = document.getElementById('chatId').value;

  if (userToBan.length <= 0) {
    var x = document.getElementById("banerror");
    x.innerHTML = "\tEnter the Username of the user you wish to ban!";
    return;
  }

  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var returncode = this.responseText;
      if (returncode == "0") {
        var x = document.getElementById("banerror");
        x.innerHTML = "\t" + userToBan + " successfully banned!";
        document.getElementById('userToBan').value = "";
      } else if (returncode == "1") {
        x = document.getElementById("banerror");
        x.innerHTML = "\tMissing Variables";
      } else if (returncode == "2") {
        x = document.getElementById("banerror");
        x.innerHTML = "\t" + userToBan + " does not exist!";
      } else if (returncode == "3") {
        window.location.href = "main.php";
      } else if (returncode == "4") {
        x = document.getElementById("banerror");
        x.innerHTML = "\t" + userToBan + " is already banned!";
      } else if (returncode == "5") {
        x = document.getElementById("banerror");
        x.innerHTML = "\tAn admin cannot be banned!";
      } else if (returncode == "6") {
        x = document.getElementById("banerror");
        x.innerHTML = "\tCreator can not be banned!";
      } else if (returncode == "7") {
        x = document.getElementById("banerror");
        x.innerHTML = "\tYou must be an Admin or creator to ban a user!";
      }
    }
  }

  xhr.open("POST", "processBanUser.php", true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.send("chatId=" + cid + "&userToBan=" + userToBan);
}

issue with javascript in if/else statement, seeking assistance as it's causing the script to stop working.

Answer №1

Make sure to include the statement console.log(returncode); on line 20 of your code. The variable returncode is not a string, so comparing it with strings will lead to a logical error. You can either remove the quotes in your if...else condition like this:

if ( returncode == 0 ){ }
else if (returncode == 1) {}

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

Sending messages through a Discord Bot without the use of a command

I have code that is constantly running in the background in JavaScript, 24/7. I am looking to configure a discord.js bot to send a notification message if any issues or errors occur within the code. Is there a way to send a message to any channel without ...

Error code E11000 is thrown due to a duplicate key in a Node.js application

Whenever I input data on the webpage, it syncs correctly with the database. However, when I attempt to fill out the same form again, an error occurs: { "code": 11000, "index": 0, "errmsg": "E11000 duplicate key error collection: test.creates i ...

When using Next.js and Express.js together, CORS error may occur, causing API queries to only function properly during build

I am currently working on a project that involves using Next.js for the front-end and Express.js for the back-end. Front-end Setup The 'pages' directory contains an 'index.js' file where I have implemented the following code snippet: ...

Retrieve data from an AJAX call and PHP script upon successful completion

Utilizing AJAX (jQuery), my aim is to submit a form to user-ajax.php and expect the page to echo back a response like "success". In my AJAX code, I am checking the response value for success but it's not working as expected. Below is the PHP code snip ...

Running AngularJS controllers should only occur once the initialization process has been fully completed

I am facing a situation where I need to load some essential global data before any controller is triggered in my AngularJS application. This essentially means resolving dependencies on a global level within AngularJS. As an example, let's consider a ...

Customizing the style of an element in Vue depending on the size of the window

I am struggling to update the appearance of an HTML element when the window size is below 500px. Currently, I have a computed property that sets a background-image for the element. I attempted to use an if statement within the computed property to check if ...

Is a Singleton really necessary for my situation?

I am currently developing a Firefox extension that requires keeping multiple windows synchronized with the same information. The toolbar in each window queries a remote server periodically, but since Firefox windows are isolated environments with their own ...

Inconsistencies in latency experienced when making calls to Google Sheets V4 API

Recently, I've been encountering latency issues with the following code: var latency = Date.now(); const sheetFile = await google.sheets({version: 'v4', auth}); var result = await sheetFile.spreadsheets.values.get({spreadsheetId: shee ...

Conceal a request URL within JavaScript through the use of Laravel/Ajax

I have an idea that I'm not sure is great or even feasible, but I really need to make it work. I am attempting to obfuscate a URL that needs to be used in a Javascript function as a parameter. This is what I currently have: <script> myFunction ...

Is it possible for a hybrid app using Angular 7/1.x to enable Hot Module Replacement (H

Having trouble implementing HMR on a hybrid Angular application using the downgradeModule strategy. I previously sought help from a similar question on Stack Overflow Can an Angular 5/1.x hybrid app support HMR? but didn't find a satisfactory answer. ...

What are the steps for loading JSON data into a select dropdown with the help of AJAX?

I am trying to create a dropdown list of schools using the select tag. Currently, I have hard coded values for the list, but I want to fetch the data from a RESTful service instead. Can someone please provide guidance on how to achieve this? <html& ...

How can I resolve the issue of not returning anything ondrop in my code?

Whenever I drop my div containing an image, I don't see anything. And when I try to access its ID, I get a null value. How can I extract information from a div with an image and append a row with it? For code samples or to check the codepen example, v ...

What is preventing X-editable from initiating an AJAX request to transmit the edited information?

Embedding the x-editable: Including in the HTML: <a class='doc_title editable' id='doc_title_12345' data-name="doc[title]" data-title="Enter doc title" data-type="text" data-url='/docs/12345' href='#doc_title_12345&a ...

tips for passing a string array to an actionresult

I've been struggling with a variable that is a string[] parameter. Despite my attempts to push values in the actionresult, I haven't been able to successfully match the string[] parameter. Here's what my ajax code looks like: var panels ...

Toggle button to create a fade in/out effect

Below is the HTML code snippet: <html> <head> <Script type = "text/javascript" src = "CprMdlrSrch.js"></Script> <link type="text/css"rel="stylesheet"href="CprMdlrSrch.css"/> </head> <body> <div id=" ...

Enhance CSS delivery for the items listed below

Reduce the delay caused by rendering JavaScript and CSS above-the-fold. There are 16 CSS resources currently blocking the rendering of your page. This delay could be affecting the loading time of your content. To improve this issue, consider deferring or ...

Experiencing the "Module not found" issue while incorporating SCSS into React applications

I attempted to apply a SCSS style to my "Logo.js" component, but I am still unable to resolve the error that keeps popping up: ERROR in ./src/components/Logo/Logo.js 5:0-19 Module not found: Error: Can't locate 'logo.scss' in '/Users/a ...

No changes will be made to the database entry

Currently facing an issue where no values are being updated on a specific ID as specified (hardcoded) in the WHERE clause. Can anyone point out what might be going wrong? I have a form with 7 fields to fill out. At the moment, I am focusing on getting th ...

Stack screen not visible on React Native navigation

I'm currently utilizing the React Native Navigation library for routing. However, I've encountered an issue with the code below that doesn't seem to be functioning as expected. My objective is to set up two screens - one for login and the o ...

Calculate the duration in seconds using the console

Is it possible to display the time of an action in seconds instead of milliseconds using console.time? Below is my code: console.log('start load cache'); console.time('cache load ok executed in') // loading from mongo console.timeEnd( ...