Window alert() Method

Hey! I’m a beginner so be patient with me :D! I have a problem with my alert ().
I want it to alert if the user has entered the wrong login information, but instead it warns regardless of what the user enters. That is, both when the user fills in the wrong information, nothing at all AND the correct information. Not only that, it seems to be in an endless loop, I need to shut down the browser for the alert to stop.

this is my JS:

$(document).ready(function() {
  $("#knapp").click(function() {
    var user = $("#user").val();
    var password = $("#password").val();
    $.get("", data => {
      data.forEach(students => {

        if (user == students.login.username && password == students.login.password) //villkor

          window.location = ("kurser.html"); //kodblock som ska köras om villkoret är sant
        else  {
          alert("fel användarnamn eller lösenord");

You are getting a json file with 184 students in it. Then iterating over that, so even if the user inputs the correct username and password, the alert will fire until it gets to a matching student.

You should consider a different approach here most likely.

So how do I get the alert to fire only when the user enter the wrong information?
Is the problem in my for-loop? I thought that the else-statement only was suppose to fire when the if-statement was wrong?

The best way would be to try to get just the single user’s user name and password from the database. If you get a result do the window.location if no result returned then alert.

Otherwise, you could iterate over the results you are getting now something like:

let userFound = false;

data.forEach( students => {
  if (user == students.login.username && password == students.login.password) {
    userFound = true;

if (userFound) {
  //do stuff if a match 
} else {
  alert("Your message");

The downside to the second approach is you would be iterating over all the students. If there were a a larger group of people that could be logging in, thousands or millions of people, this would be horribly inefficient. That is why the better way is to try to search the database for just the single user rather than retrieve a list of everyone .