Danny Lewis
Danny Lewis

Reputation: 23

HTML Submit form only executing one JavaScript function on submit

Good Afternoon,

I am currently in the process of creating a website using HTML, PHP and JavaScript, and I have run into an issue when trying to check for duplicate usernames in a database. Currently, I have a form which uses the following code to call two javascript functions on submit.

<form onsubmit="return (checkValid() && usernameCheck())" action="create.php" method="post" id="registerForm">

The javascript code is then present at the bottom of the body tag, within script tags, and is the following.

<script>

            var pass = document.getElementById('passVal').value;
            var confPass = document.getElementById('confPassVal').value;
            var error = document.getElementById('errorMsg');
            var result = true;

        function checkValid(){ 

            if(pass !== confPass)
            {
                error.type = "text";
                error.value = "Passwords do not match!";
                error.style.backgroundColor = "#E34234";
                document.getElementById('passVal').style.borderColor = "#E34234";
                document.getElementById('confPassVal').style.borderColor = "#E34234";
                result = false;
            }

            return result;

        }

            function usernameCheck()
            {

              var username = document.getElementById('userName').value;
              var j = checkName(username);
              console.log(j);

              if ( j == "taken" ) {
                error.type = "text";
                error.value = "Username Already Exists, Please choose an alternative.";
                error.style.backgroundColor = "#E34234";
                document.getElementById('userName').style.borderColor = "#E34234";
                console.log(j);
                result = false;
              }
              if ( j == "available" ) {
                console.log(j);
                result = true;
              }

                return result;
            }

        function checkName(uname) {

              if (window.XMLHttpRequest) {
                xhttp = new XMLHttpRequest();
              } else {
                xhttp = new ActiveXObject("Microsoft.XMLHTTP");
              }
              var httpURL = "checkUserName.php?n=" + uname;
              xhttp.open("GET",httpURL,false);
              xhttp.send();
              return xhttp.responseText;
            }

    </script>

The issue I am having is that the second JavaScript function is not executing, even though it is being called in the onsubmit function. Because of this, the third function is also not executing, as this function is called within the second function. The second function submits a GET value with the username input in the HTML form to a PHP script. The PHP script then checks the database to see if this user exists, and returns a value based on if this is true or not. The code below shows the PHP script.

<?php
session_start();

require 'sql.php';

header('Content-type: text/plain');
$userName = $_GET['n'];

$query =  "SELECT username FROM users where username='$username'";
$checkun = $conn->query($query);
while ($row = $checkun->fetch_assoc()) {
    if ($row > 0) 
    {
        exit('taken');
    } else
    {
        exit('available');
    }
}

?>

The first JavaScript function successfully executes, which is used to check if the password fields match. This function either returns a false value if the password fields do not match (hence the second function will not execute), or a true value if they do. Even if the first function returns true, the next function does not execute, and the form submits without running this second function.

I would be grateful if someone more experienced than me (I have only been practising web development for a few months) could highlight if there are any errors in my method, and possibly help me with a solution.

Thank you for taking the time to read this!

Upvotes: 2

Views: 156

Answers (1)

Apps-n-Add-Ons
Apps-n-Add-Ons

Reputation: 2146

When you say "the second function does not run" - do you mean that you get no response in the JS? I would imagine that to be true as you will NEVER have a match in your MySQL query - and, you don't have your 'catchall' in the right place.

This looks like a first learning experience for you to get data from a database, so I won't harp on the fact that you are WIDE OPEN for SQL injection attacks, though I will say that you must NOT use this code on any open system where there are real users (you need to learn how to protect against those attacks - there's loads of data on that on SO)!

So, your first step in at least getting the 'second function' to 'work'.....

<?php
session_start();
require 'sql.php';
header('Content-type: text/plain');
// $userName = $_GET['n']; // <<<==== here you use with a capital
$username = $_GET['n']; // let's change it to be the same
$query =  "SELECT username FROM users where username='$username'"; // now, we have a chance...
$checkun = $conn->query($query);
while ($row = $checkun->fetch_assoc()) {
    if ($row > 0) 
    {
        exit('taken');
    }
}
// Here is where to put your 'catchall' in case you don't get anything from the query (what you have won't ever give 'available')
exit('available');
?>

Upvotes: 1

Related Questions