skip to Main Content

I trying to making form validation using JavaScript + AJAX, but it’s not working.

What I am gonna wrong plz solve my problem.

function validateform() {
  $.ajax({
    url: '../api?type=validate_refercode&refer_code=' + $('#refer_code').val() + '',
    success: function(data) {
      if (data == 'fail') {
        return false;
      }
    }
  });
   
  return true;
}
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
<form method="POST" onsubmit="return validateform()">
  <div class="col-lg-6">
    <div class="floating-label form-group">
      <input class="floating-input form-control" type="text" id="refer_code" placeholder=" ">
      <label>Referral Code</label>
    </div>
  </div>
  <button type="submit" id="submit" name="submit" class="btn btn-white">Sign Up</button>
</form>

2

Answers


  1. Use event.preventDefault() because the form is getting submitted before the AJAX request is completed and the success callback is executed.

    function validateform(event) {
    
      event.preventDefault(); // Prevent form submission
    
      $.ajax({
    
        url: '../api?type=validate_refercode&refer_code=' + $('#refer_code').val(),
    
        success: function(data) {
          if (data === 'fail') {
            console.log('Validation failed');
          } else {
            $('form').submit();
          }
        }
    
      });
    
    }
    
    Login or Signup to reply.
  2. Some will complain about my abstractions; but, this is the layout i typically use for JS. It allows you to add more functions to it if needed.

    Avoid using inline functions and use eventlisteners instead. Inline functions will likely break your CSP (which protects you from XSS) and inline don’t stack whereas eventlisteners do.

    Also use html validation by using "pattern" or "required".
    My example uses pure JS and doesn’t need jQuery.

    // utility function for readability
    const qs = (el) => document.querySelector(el);
    
    // wait for DOM to completely load before running
    // the following JS
    document.addEventListener('DOMContentLoaded', () => {
    
    // a function should do one task and do it well
    const getReferralCode = () => qs('input#refer_code').value;
    
    const addFormInitListener = () => {
      const $referral_form = qs('form#referral_form');
      $referral_form.addEventListener('submit', async (e) => {
        const params = new URLSearchParams({
          type: 'validate_refer',
          refer_code: getReferralCode()
        });
        const url = `../api?${params.toString()}`;
        const response = await fetch(url);
        const data = await response.text();
        
        // place logic here - if failed server validation then return false and attach the appropiate error boxes to fields
        // prevents form from being submitted
        return false;
      }); 
    }
    
    // place all your listeners on page load inside this function
    const addInitListeners = () => {
      addFormInitListener();
    }
    
    // place all things you want to run on startup of page
    const init = () => {
      addInitListeners(); 
    }
    
    init();
    
    });
    <script src="https://code.jquery.com/jquery-3.7.0.js"></script>
    <form id="referral_form" method="POST">
      <div class="col-lg-6">
        <div class="floating-label form-group">
          <input class="floating-input form-control" type="text" id="refer_code" placeholder=" " required>
          <label>Referral Code</label>
        </div>
      </div>
      <button type="submit" id="submit" name="submit" class="btn btn-white">Sign Up</button>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search