HTML Submit form only executing one JavaScript function on submit












2















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!










share|improve this question

























  • In a a && b boolean expression, whatever's after && will not be executed if a resolves to false. See Short-circuit evaluation.

    – Jeto
    Nov 23 '18 at 12:10













  • XMLHttpRequest is async so the function checkName() won't return immediately

    – Satpal
    Nov 23 '18 at 12:11













  • There seems to be some confusion in your statement. You are saying if first function returns false then form doesn't submit, then you say as second function doesn't run form always submits.

    – Diljohn5741
    Nov 23 '18 at 12:12











  • Sorry for the confusion. The first function checks if the two passwords are correct. If so, the value returned to the form is true, thus the second function should be run. To test the second function, I have been running tests so that the first function always returns true. Even if the first function returns as true, the second function does not run, hence the confusion. Hope that clears things up a bit :)

    – Danny Lewis
    Nov 23 '18 at 12:26
















2















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!










share|improve this question

























  • In a a && b boolean expression, whatever's after && will not be executed if a resolves to false. See Short-circuit evaluation.

    – Jeto
    Nov 23 '18 at 12:10













  • XMLHttpRequest is async so the function checkName() won't return immediately

    – Satpal
    Nov 23 '18 at 12:11













  • There seems to be some confusion in your statement. You are saying if first function returns false then form doesn't submit, then you say as second function doesn't run form always submits.

    – Diljohn5741
    Nov 23 '18 at 12:12











  • Sorry for the confusion. The first function checks if the two passwords are correct. If so, the value returned to the form is true, thus the second function should be run. To test the second function, I have been running tests so that the first function always returns true. Even if the first function returns as true, the second function does not run, hence the confusion. Hope that clears things up a bit :)

    – Danny Lewis
    Nov 23 '18 at 12:26














2












2








2








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!










share|improve this question
















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!







javascript php jquery html function






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 12:31







Danny Lewis

















asked Nov 23 '18 at 11:58









Danny LewisDanny Lewis

133




133













  • In a a && b boolean expression, whatever's after && will not be executed if a resolves to false. See Short-circuit evaluation.

    – Jeto
    Nov 23 '18 at 12:10













  • XMLHttpRequest is async so the function checkName() won't return immediately

    – Satpal
    Nov 23 '18 at 12:11













  • There seems to be some confusion in your statement. You are saying if first function returns false then form doesn't submit, then you say as second function doesn't run form always submits.

    – Diljohn5741
    Nov 23 '18 at 12:12











  • Sorry for the confusion. The first function checks if the two passwords are correct. If so, the value returned to the form is true, thus the second function should be run. To test the second function, I have been running tests so that the first function always returns true. Even if the first function returns as true, the second function does not run, hence the confusion. Hope that clears things up a bit :)

    – Danny Lewis
    Nov 23 '18 at 12:26



















  • In a a && b boolean expression, whatever's after && will not be executed if a resolves to false. See Short-circuit evaluation.

    – Jeto
    Nov 23 '18 at 12:10













  • XMLHttpRequest is async so the function checkName() won't return immediately

    – Satpal
    Nov 23 '18 at 12:11













  • There seems to be some confusion in your statement. You are saying if first function returns false then form doesn't submit, then you say as second function doesn't run form always submits.

    – Diljohn5741
    Nov 23 '18 at 12:12











  • Sorry for the confusion. The first function checks if the two passwords are correct. If so, the value returned to the form is true, thus the second function should be run. To test the second function, I have been running tests so that the first function always returns true. Even if the first function returns as true, the second function does not run, hence the confusion. Hope that clears things up a bit :)

    – Danny Lewis
    Nov 23 '18 at 12:26

















In a a && b boolean expression, whatever's after && will not be executed if a resolves to false. See Short-circuit evaluation.

– Jeto
Nov 23 '18 at 12:10







In a a && b boolean expression, whatever's after && will not be executed if a resolves to false. See Short-circuit evaluation.

– Jeto
Nov 23 '18 at 12:10















XMLHttpRequest is async so the function checkName() won't return immediately

– Satpal
Nov 23 '18 at 12:11







XMLHttpRequest is async so the function checkName() won't return immediately

– Satpal
Nov 23 '18 at 12:11















There seems to be some confusion in your statement. You are saying if first function returns false then form doesn't submit, then you say as second function doesn't run form always submits.

– Diljohn5741
Nov 23 '18 at 12:12





There seems to be some confusion in your statement. You are saying if first function returns false then form doesn't submit, then you say as second function doesn't run form always submits.

– Diljohn5741
Nov 23 '18 at 12:12













Sorry for the confusion. The first function checks if the two passwords are correct. If so, the value returned to the form is true, thus the second function should be run. To test the second function, I have been running tests so that the first function always returns true. Even if the first function returns as true, the second function does not run, hence the confusion. Hope that clears things up a bit :)

– Danny Lewis
Nov 23 '18 at 12:26





Sorry for the confusion. The first function checks if the two passwords are correct. If so, the value returned to the form is true, thus the second function should be run. To test the second function, I have been running tests so that the first function always returns true. Even if the first function returns as true, the second function does not run, hence the confusion. Hope that clears things up a bit :)

– Danny Lewis
Nov 23 '18 at 12:26












1 Answer
1






active

oldest

votes


















1














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');
?>





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53446309%2fhtml-submit-form-only-executing-one-javascript-function-on-submit%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    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');
    ?>





    share|improve this answer




























      1














      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');
      ?>





      share|improve this answer


























        1












        1








        1







        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');
        ?>





        share|improve this answer













        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');
        ?>






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 23 '18 at 15:34









        CFP SupportCFP Support

        1,2001923




        1,2001923






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53446309%2fhtml-submit-form-only-executing-one-javascript-function-on-submit%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Feedback on college project

            Futebolista

            Albești (Vaslui)