My code operates successfully only on the initial execution

I am encountering an issue with my function regarding a login form validation using JSON data. The code seems to be working correctly, but only when I input the correct data immediately after refreshing the page. For example, if I enter an incorrect login/password combination, I receive an error, but then if I try again with the correct credentials, nothing happens.

Your assistance would be greatly appreciated. Below is the JavaScript code I am currently using:

//JSON validation
function validation(username, password){
    var alert = document.getElementById("invalid-data");
    data = JSON.parse(data);

    for (var i=0; i < data.length; i++) {
        if (username == data[i].login && password == data[i].password) {
            window.open("panel.html", "_self");
        } else {
            alert.style.display = "block";
        }
    }
}

//Form validation
function getLoginInfo() {
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;

    validation(username, password);
}

var button = document.getElementById("login-button");
button.addEventListener("click", getLoginInfo);

Answer №1

One potential issue that may be causing your problem is the line data = JSON.parse(data);. This line of code can cause issues because it reassigns the parsed data back to the variable data, which can lead to errors in subsequent JSON parsing operations. To avoid this problem, consider storing the parsed data in a separate variable, as shown below:

//JSON validation
function validateCredentials(username, password){
    var alert = document.getElementById("invalid-data");
    var parsedData = JSON.parse(data);

    for (var i=0; i < parsedData.length; i++) {
        if (username == parsedData[i].login && password == parsedData[i].password) {
            window.open("panel.html", "_self");
        } else {
            alert.style.display = "block";
        }
    }
}

//Form validation
function getLoginInfo() {
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;

    validateCredentials(username, password);
}

var button = document.getElementById("login-button");
button.addEventListener("click", getLoginInfo);

Answer №2

This particular function faced an issue

info = JSON.parse(info);

The problem stemmed from it being confined within a function scope. By making it global, the functionality improved seamlessly.

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

Cannot load the next page using jQuery ajax

I am working on a project with an index.html file that includes a nav menu, header, footer, and a div.content where jQuery is used to parse the html of page1.html. Initially, page1.html loads perfectly. However, I encountered an issue when trying to imple ...

Provide alternative styling through css in instances where the Google Books API does not provide an image

How can I modify the CSS code to display the author and title of a book when there is no image available from the Google Books API? Currently, users see a custom image linked here, but it's not clear what it represents without the name and author inf ...

Obtain the initial JSON element containing a designated ID within a JSON array using Microsoft Flow

My Parse JSON action has the schema below: { "type": "object", "properties": { "employees": { "type": "array", "items": { "type": "object", "properties": { "id": { ...

What language should be used for JSON data formats?

I am dealing with a JSON file named myjson.cfg that has the following structure: { "values": { "a": 1, "b": 2, "c": 3, "d": 4 }, "sales": [ { "a": 0, "b": 0, "c": 0, "d": 0, ...

Learn the process of updating an Xero invoice seamlessly with the xero-Node integration

After successfully integrating Xero with my app for accounting and billing purposes, I am now looking to update a previous invoice that was created in the past on Xero. Is there a solution available for this? Any suggestions would be greatly appreciated. ...

What is the purpose of wrapping my EventEmitter's on function when I pass/expose it?

My software interacts with various devices using different methods like serial (such as USB CDC / Virtual COM port) and TCP (like telnet). To simplify the process, I have created a higher-level interface to abstract this functionality. This way, other sect ...

I'm baffled by the unexpected result I'm getting when using 'foreach' in node.js

Recently delving into node.js, I've encountered a puzzling issue. I'm perplexed as to why my output appears as: ciao data data instead of: data data ciao Below is the code causing this unexpected output: fs.readdir("sender", (err, fil ...

Focusing on animation and keyframes within individual div elements

I encountered an issue while trying to add hover functionality to pause my pure CSS slider. Initially, I had the pausing feature working but then I wanted to include a div displaying that it is paused. However, I realized that one element cannot trigger an ...

Can Javascript be invoked from a hyperlink?

Similar Question: How to handle URL anchor change event in JavaScript Can a JavaScript function be triggered by clicking on an anchor tag? For example, if you visit www.site.com/index.html#function1, would function1 automatically run? ...

Having trouble accessing the link from the dropdown list in Selenium

While trying to select a link from a dropdown menu, I am facing an issue with Selenium. The element is being located successfully, but it cannot be interacted with and the following exception is thrown: Error in thread "main" org.openqa.selenium.ElementNo ...

Larger icon graphics

Is it possible to increase the size of Glyphicons in Twitter Bootstrap 3.0 without using the btn-lg class? I found this code that makes glyphicons big: <button type="button" class="btn btn-default btn-lg"> <span class="glyphicon glyphicon-th- ...

Is it possible to set all UI forms to a readonly/disable mode?

We have a specific requirement where, if the user's access level is set to "READ ONLY", all form input elements should be made readonly. Our coding approach involves using a template HTML that contains widgets which are referenced in the correspondin ...

Displaying markers on a Google map by fetching data from a MySQL database in PHP

The image attached here serves as an example. You can view it here. Currently, I display locations on a map in an HTML page with static code like: Here is the JavaScript code to load the map on the page: <script type="text/javascript" src="https://ma ...

What should I do when using _.extend() in express - override or add in fields?

When an object is extended by another object with values set for some of the extended fields, will it be rewritten or will the new values be added? For example: const PATCH_REQUEST_SCHEMA = { 'type': 'object', 'title' ...

Pre-requisites verification in TypeScript

I have a typescript class with various methods for checking variable types. How can I determine which method to use at the beginning of the doProcess() for processing the input? class MyClass { public static arr : any[] = []; // main method public stati ...

Traversal of a binary tree in the order of visitation specified by the In

My task was to create a function that traverses a binary tree and returns an array of all its values in inorder. The code provided is: interface BinTree { root: number; left?: BinTree; right?: BinTree; }; const TreeInArray =(t:BinTree):number[] =>{ ...

How can I simulate or manipulate the element's scrollHeight and clientHeight in testing scenarios?

In my JavaScript code, I have a function that checks if an HTML paragraph element, 'el', is a certain size by comparing its scrollHeight and clientHeight properties: function isOverflow(element: string): boolean { const el = document.getEleme ...

Attempting to successfully upload this Angular 7 form to my TypeScript code. Making use of ngForm and [(ngModel)] to achieve this

I am having trouble passing form information using the onSubmit() function. It seems to be undefined when I try to execute it initially. Could there be a syntax error that I'm missing? <form class="gf-formbox" name="credentials" (ngSubmit)="onSubm ...

Tips for improving the focus of the bootstrap datetime picker?

I have integrated the Bootstrap datetime picker (bootstrap-datetimepicker.min.js) into my code. Within the DIV tag, I have included the class="modal fade" to open the first popup. In the first popup, there is a datetime picker. When clicking on the picker ...

Struggling to retrieve information from a deeply nested array within an Ansible playbook

I am having trouble extracting the values of vs_name for each item in the array list. There seems to be an issue with my code, but I can't seem to pinpoint it. Below is the desired output that I need to parse: ok: [localhost] => { "msg" ...