Hazel Meehan
Hazel Meehan

Reputation: 23

Opening page from javascript is not working

I am trying to make a login using js, I know this isn't secure it's just for school - they require it.

If username and password are correct I want it to open my photos page, this isn't happening.

As far as I can tell everything else is working just fine, it collects and compares data correctly, but won't open the new page. I have tried variations on the this.location.href such as window.location and location.replace.

I have also tried changing the URL using full URL and photos.php

The function is called from a click within the HTML :

<button type="submit" onclick="checkPassword()" class="button">Login</button>

This is the JavaScript:

function check() {   //onclick
    var username = "test";
    var password = "admin";
    var usernameEntered = document.getElementById("username").value;
    var passwordEntered = document.getElementById("password").value;

    if (usernameEntered == username && passwordEntered == password) {
        this.location.href = "http://localhost/photos-v4/photos.php";
    } else {
        alert("Incorrect username or password");
    }
}

Upvotes: 2

Views: 246

Answers (2)

Hazel Meehan
Hazel Meehan

Reputation: 23

The problem is in the HTML.

type = "submit" is used to send the data to a new place meaning that the data isn't being captured by the JavaScript.

A solution to this is replacing submit with resetwhich clears the form and, lets the js get the data it needs.

You can read more about HTML buttons here: https://html.com/attributes/button-type/

Upvotes: 0

Ulrich Dohou
Ulrich Dohou

Reputation: 1559

Here a some ways to do it

Open in new page

window.open('http://localhost/photos-v4/photos.php', '_blank').location;

Open in the current tag

window.location.href = 'http://localhost/photos-v4/photos.php'

Upvotes: 1

Related Questions