My AJAX disables another JavScript function

I have an HTML registration form with javascript fonctions to check if it was filled and correctly :

	include_once 'header.php';
?><!DOCTYPE html>
  <title> JavaScript </title>
   <script src=""></script>
	  <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
	  <script type="text/javascript" src="js/jquery-ui.min.js"></script>
	  <script type="text/css" src="js/jquery-ui.css"></script>
	  <link rel="stylesheet" href="">

<script type="text/javascript">
	//check username availability using AJAx
		username = $("#username").val(); //Insert username input field value intu username variable
		if(username.length >0){
		   checkUsernameAvailability(username); //This function will chack username avgailability
	});//End check username availability using AJAx

	  //Declare an empty array which will contain all empty fields which must be filled
	var unfilled = [];
	// Reset counter
    var i = 0;
	 if (firstname.value.length == 0)
	   unfilled[i] = 'first name'+'\n';

	 if (lastname.value.length == 0)
	   unfilled[i] = 'last name'+'\n';
	 if (email.value.length == 0)
	   unfilled[i] = 'email'+'\n';
	 if (username.value.length == 0)
	   unfilled[i] = 'username'+'\n';
	 if (pwd.value.length == 0)
	   unfilled[i] = 'password'+'\n';

	  //check if all form fields are not empty
	 if(unfilled.length > 0)
		 //If not all fields are filled - stop default action - the form data processing
	    var message = '';
	    for( var i=0; i<=unfilled.length-1; i++)
		    message = message + unfilled[i];
		if(unfilled.length == 1){
		    alert ('The following field must be filled :'+'\n'+message);
		}else {
			alert ('The following '+i+'  field must be filled :'+'\n'+message);
	}); //End button click
	   });//End ready

	  function checkUsernameAvailability(username){
			   document.getElementById("button").disabled = true;
			   document.getElementById("button").style.cursor = "not-allowed";
			    document.getElementById("button").disabled = false;
				document.getElementById("button").style.cursor = "pointer";

  <section class="main-container">
     <div id="" class="main-wrapper">
			<h2>Sign Up</h2>
	     	<form class="signup-form" method="post" id="form" action="includes/">
				<input type="text" id='firstname' name="firstname" placeholder="First Name">
				<input type="text" id="lastname" name="lastname" placeholder="Last Name">
				<input type="email" id="email" name="email" placeholder="E-mail">
				<input autocomplete="off" type="text" id="username" name="username" placeholder="Username" pattern="[A-Za-z0-9.-_]{5,10}">
				<!-- The following div will contain the data telling registrants if username is available -->
				<div id="status" style="text-align: center; font-family: david;"></div>	
			    <input type="password" id="pwd" name="pwd" placeholder=" Password">
				<button type="submit" name="submit" id="button" class= "disabled">Sign Up</button>


And Here is the page which checks if username is available

    $username = ""; //Declare the variable which will get the data from the AJAX script

		 $username = strip_tags($_POST['username']);

		 // Check if the username is already in use by another user
         // Constract the sql query and prepare it.
				$sql = "SELECT username FROM users WHERE username = :username LIMIT 1";

				$stmt = $db->prepare($sql);
				//Bind the provided username to the query
				$stmt->bindValue(':username', $username);
				//Get the query results.
				$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
				//Count how many users with $username  username exist.
				if(count($row) > 0){
					//If count($row) > 0 -> username taken
					//header("Location: ../signup.php?signup=usernametaken ");
					echo $username." - <b style='color: red; font-family:arial;'>username taken</b>";
				  echo $username." - <b style='color: green; font-family:arial;'>Username available</b>";

when I click sign up and a field / fields is/ are empty - a JQueryfunction alerts a mesage to let the user know which input fields were left empty

However, when username field is filled and username is available
the fonction which alerts in case a n input field is empty doesn’t work

Why does AJAx disables the JQueryfunction

how can I solve the problem

Hi @erezvol, this is because the function checking for unfilled fields throws an error and doesn’t run to the point where the default event would get prevented, so the form just gets submitted:

Uncaught TypeError: Cannot read property ‘length’ of undefined

This happens for the variable username, which is getting set to a string here:

username = $("#username").val()

Before that, username would refer to the DOM element with the ID username, having a value with a length. It is generally a bad idea to rely on such implicit globals; better use proper variables for this:

var unfilled = []
var firstname = document.getElementById('firstname')
// etc...
var username = document.getElementById('username')

// You can now safely check for the element values:
if (!username.value) {

Or using jQuery:

if (!$('#username').val()) {

BTW you’re using a very old version of jQuery, which is currently at 3.6.0… I’d recommend to upgrade if possible.


And the OP is including jQuery twice. This should also be addressed.

1 Like

Thank you very much m3g4p0p
How do you get this error message ?

I use firefox and I searched the degugger for this error message. I get none

The console is getting cleared when leaving the page (as is the case when submitting the form), but you can check “Persist Logs” in the console settings (the gear icon) to prevent this.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.