Valid method of confirming a user's login status

Using AJAX requests, I have implemented a user area on my website. The "Log off" button is supposed to be displayed only when the user is logged in.

Here is the AJAX request for logging in a user:

function requestSI() {
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
        document.getElementById("popup_login").innerHTML = "<img src='img/index/cross.png' id='close' onclick ='hidelogin()' /><div id='color2'></div><h2 id=login_title>";
        document.getElementById("popup_login").innerHTML += this.responseText;
        if (isUserLogged()){
            var x = document.getElementById("log_off");
            x.classList.remove("inactive_logoff");
            x.classList.add("active_logoff");
        }
    }
};

var login_fieldSI = encodeURIComponent(document.getElementById("login_fieldSI").value);
var password_fieldSI = encodeURIComponent(document.getElementById("password_fieldSI").value);

xhr.open("POST", "php/login.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("Login_fieldSI="+login_fieldSI+"&Password_fieldSI="+password_fieldSI);
}

And here is the AJAX request to check if a user is connected:

function isUserLogged(){
    var xhr = getXMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
            alert(this.responseText);
            if (this.responseText == "true") return true;
            else return false;
        }
    };
    xhr.open("POST", "php/is_user_connected.php", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(null);
}

The "Log off" button is not displaying for some unknown reason.

Answer №1

     function makeLoginRequest() {
    var request = createXMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState == 4 && (request.status == 200 || request.status == 0)) {
            document.getElementById("popup_login").innerHTML = "<img src='img/index/cross.png' id='close' onclick ='hideLogin()' /><div id='color2'></div><h2 id=login_title>";
            document.getElementById("popup_login").innerHTML += this.responseText;
    checkUserStatus();           
        }
    };

    var loginField = encodeURIComponent(document.getElementById("login_fieldSI").value);
    var passwordField = encodeURIComponent(document.getElementById("password_fieldSI").value);

    request.open("POST", "php/login.php", true);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    request.send("Login_field="+loginField+"&Password_field="+passwordField);
    }
    ----------
    function checkUserStatus(){
        var statusRequest = createXMLHttpRequest();
        statusRequest.onreadystatechange = function() {
            if (statusRequest.readyState == 4 && (statusRequest.status == 200 || statusRequest.status == 0)) {
                alert(this.responseText);
                if (this.responseText == "true"){
                    alert("ok");                     
                alert("test function");
                var x = document.getElementById("log_off");
                x.classList.remove("inative_logoff");
                x.classList.add("active_logoff");                
                }
                else {
                   //do other code..
                }
            }
        };
        statusRequest.open("POST", "php/is_user_connected.php", true);
        statusRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        statusRequest.send(null);
    }

Answer №2

Consider using the following: if (isUserLogged() == true){ in place of if (isUserLogged()){

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

Exploring the functionality of Async Storage in React Native for efficient data saving purposes

I'm completely new to working with Async and async storage. I am a bit lost and unsure of how to proceed, but my main objective is to use setWorkouts() to assign workouts based on the values I retrieve from asyncstorage, and then save these workouts. ...

The command '.' is unable to be executed as an internal or external command, executable program, or batch file when using npm start -- -e=stag -c=it

After executing the command shown below npm start -- -e=stag -c=it An error is generated: ./scripts/start.js -e=stag -c=it '.' is not recognized as an internal or external command, operable program or batch file. What can be done to resolve th ...

Verifying a form submission using a personalized model popup

I have several delete forms in my application that I want to confirm using javascript/jQuery before proceeding. An easy way to do this is: $('form.confirm-form').submit(function(){ return confirm('Are you sure?'); }); This method ...

Trigger a function on q-select change using onChange event (Quasar Framework)

I'm trying to get the function to run when I change the selected value, but it's not working. How can I solve this issue? Below is the code I am using: <q-select v-model="single" :options="['def', 'abc', ...

potential issues with memory leakage and browser crashes in three.js

Currently working on an app that features a spherical panorama photo with a jpg size of around 4Mb. Throughout the development process, I find myself constantly refreshing the page to see changes and browsing through various three.js example pages for insp ...

Retrieve the initial image from every JSON data point

Searching for a way to fetch the first image from each post in the JSON object? Check out the Tumblr API Documentation Currently, the provided code displays content from only the first post. The goal is to display the first image from all posts. $.ajax({ ...

Looking to achieve a scroll effect with mix-blend-mode using JavaScript?

I am seeking a method to adjust the background color of a specific element based on the background itself. While CSS offers the mix-blend-mode property, I am looking to specify the color manually. Ideally, I would like to achieve the same effect using an ...

Having difficulty transitioning Express Controller logic to a Service Class

Within the User Controller, there is a function that processes a GET request to /user/ and retrieves two JSON objects randomly from a MongoDB collection. Here is how the response looks like inside the controller: [{ "name": "User 1" ...

Vue.js is displaying the error message "Expected Object, got Array" when the length appears as undefined

I have an app where users input style codes into a field. I want to create a popup confirmation modal that displays a message with the number of style codes provided. The code I currently have is: <template> <h4>Style Number</h4> <For ...

When PHP echo of json_encode triggers an error, AJAX status 200 will be raised

Despite everything running smoothly in the program below, an AJAX error is triggered: javascript: var data = { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="026f6742656f636b6e2c616d6f">[email protect ...

Eliminating empty elements from arrays that are nested inside other arrays

I am facing a challenge with the array structure below: const obj = [ { "description": "PCS ", "children": [ null, { "name": "Son", ...

What prevents me from calling a function while it is being defined in the prototype?

I am experimenting with inheritance through an example. I want to access all properties of objects abc and pqr, so I decided to use Object.create. However, when I try to get the value of r by calling the getr() function, it doesn't seem to work as exp ...

Having trouble with Angular UI Select functionality?

I have integrated the angular ui select library from https://github.com/angular-ui/ui-select into my project. Instead of using the traditional select element, I am now utilizing the ui-select directive. This is a snippet of my code: <select class=" ...

Blur Event Triggered in Primefaces Editor

My current setup involves using JSF Mojarra 2.2.8 with PrimeFaces 5.1, where I utilize a PrimeFaces editor for text input. I am looking to automatically upload the entered text via ajax. However, the editor only supports an onchange event. I'm seekin ...

transferring data from JavaScript on the client side to Express on the server side

Using JavaScript, I have created the HTML DOM that you see in the code below. Now, my goal is to send the value of an input created in JavaScript to the server side. The server is built with node.js and express framework. Once the value is sent to the serv ...

Make changes to a section of the website?

Looking for a quick way to update content without refreshing the entire page? Clicking on links or buttons in the whitebox should fetch data from the database and display it in the redbox. As a beginner in the Laravel framework, I'm curious about the ...

The amalgamation of geometries using BufferGeometryUtils results in variations from the original model

I have encountered an issue when attempting to merge GLB model geometries with three.js using BufferGeometryUtils.mergeBufferGeometries. The new merged geometries do not always align perfectly with the original model. Furthermore, some of the geometries e ...

Incorporating Hyperlinks into Text using React I18next

I'm facing an issue with I18next. I can't seem to make links to websites work correctly using the following code: import React, { Suspense } from "react"; import i18n from "i18next"; import { initReactI18next, useTranslation, ...

What could be causing the JavaScript array to not successfully transfer to PHP?

Despite searching for solutions, I am unable to get the desired outcome. When I check my JavaScript array in the console, it appears like this: [] 0:Object stock:27 createdtime:"2016-04-08T04:00:00+0000" id:"693852404037393999" units:438 ...

Phonegap and the Importance of HTTP Requests

Having an unusual issue with Phonegap where my XMLHttpRequests are firing twice. Currently, I am working on an app that involves using XMLHttpRequests to generate a dynamic list of events for users to choose from. In addition to this, I am utilizing jQuery ...