My AJAX disables another JavScript function

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

<?php
;
	include_once 'header.php';
?><!DOCTYPE html>
<html>
 <head>
  <title> JavaScript </title>
   <script src="https://code.jquery.com/jquery-1.12.4.min.js"></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="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">

<script type="text/javascript">
 
$(document).ready(function(){
   
 
	//check username availability using AJAx
	$("#username").keyup(function(){
		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

	
	  
	$("#button").click(function(){
		  
	   
	  //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';
       i++;
	  }

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

	  //check if all form fields are not empty
	 if(unfilled.length > 0)
		{
		 event.preventDefault();
		 //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){
	     
	    $.ajax({
		   method:'POST',
			   url:'includes/process_data.php',
		   data:'username='+username,
		   success:function(data){
		   $("#status").html(data);
		   if(data.includes("taken")){
			   document.getElementById("button").disabled = true;
			   document.getElementById("button").style.cursor = "not-allowed";
		      }else{
			    document.getElementById("button").disabled = false;
				document.getElementById("button").style.cursor = "pointer";
			    }
		   }
		})
 
	  }
   
  
	 
	
  </script>
</script>
 </head>

 <body>
  <section class="main-container">
     <div id="" class="main-wrapper">
		
			<h2>Sign Up</h2>
	     	<form class="signup-form" method="post" id="form" action="includes/add_new_user.inc.php">
				<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>

            </form>
		
     </div>
	 
  </section>
 </body>
</html>

And Here is the page which checks if username is available

<?php
include('../includes/db_connect.inc.php');
    $username = ""; //Declare the variable which will get the data from the AJAX script

    if(isset($_POST['username'])){
	
		 $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);
				
				//Execute.
				$stmt->execute();
				//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>";
					//exit();
				}else{
				  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
image

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) {
  unfilled.push('username\n')
}

Or using jQuery:

if (!$('#username').val()) {
  unfilled.push('username\n')
}

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

2 Likes

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.