简体   繁体   中英

jquery ajax prevent form submit if username is unavailable

i am using this script to check username availability, it works but the form is submitted even if the username is unavailable. i tried to use event.preventdefault but, i don't know to use it correctly how can i prevent the form to be submitted?

<script>
    function checkAvailability() {
        $("#loaderIcon").show();
        jQuery.ajax({
            url: "check_availability.php",
            data: 'username=' + $("#username").val(),
            type: "POST",
            success: function(data) {
                $("#user-availability-status").html(data);
                $("#loaderIcon").hide();
            },
            error: function() {}
        });
    }
</script>

here is the form

<form id="defaultForm" action="index1.php" method="post" class="registration-form">
    Username
    <br>
    <input type="text" name="username" onBlur="checkAvailability()" id="username">
    <br><span id="user-availability-status"></span> Password
    <br>
    <input type="text" name="email" id="email">
    <br>
    <button type="submit" name="sub">Submit</button>

here is check_availability.php

<?php
    require_once("connect.php");
    if(!empty($_POST["username"])) {
      $result = mysqli_query($con,"SELECT count(*) FROM users WHERE username='" . $_POST["username"] . "'");
      $row = mysqli_fetch_row($result);
      $user_count = $row[0];
      if($user_count>0) {
         echo "<span class='status-not-available'><p style='text-align:center'> Username Not Available</p></span>";
      }
    }
?>

Remove the function call in your HTML

$(document).ready(function(){

  $("#defaultForm").submit(function(e) {
    e.preventDefault();
  $("#loaderIcon").show();
    var self = this;
    $.ajax({
            url: "check_availability.php",
            data: 'username=' + $("#username").val(),
            type: "POST"                
    }).success(function(data) {
      $("#user-availability-status").html(data);
                $("#loaderIcon").hide();
        if (data!= "<span class='status-not-available'><p style='text-align:center'> Username Not Available</p></span>")  
          self.submit();
    }).error(function() {
        alert('error');
    });
});

 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM