Search code examples
javascriptphpajaxforms

Submit form linked to ajax data result


I have my input form that collects data. I want to check if one of this input is present in my mySql db and to do this I call the procedure via AJAX.

The procedure makes a mySql query and returns a value "1" or "0" if the record exists or not. All is ok with the AJAX request.

I can check if the data returned is 1 or 0. The problem is that if the data is 0 (a record already exists) I have to avoid the submission form. But it doesn't work.

<form id="frm" name="frm" action="000.php?us=1&usop=1&ada=1" method="post" enctype='multipart/form-data'>
  <input name="elm" id="elm" type="text" style="width: 100%;" required>
  <input name="vin" id="vin" type="text" style="width: 100%; text-transform: uppercase;" required>
  <button class="btn-success" type="submit" id="go" name="btn-login">Go!</button>
</form>
(function() {
  'use strict';
  window.addEventListener('load', function() {
    var forms = document.getElementsByClassName('needs-validation');
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();

$(".btn-success").click(function() {
  $.ajax({
    type: "POST",
    data: {
      q: $('#elm').val(),
    },
    url: "getunique.php",
    success: function(data) {
      if (data === '0') {
        $("#elm").val("");
        alert("duplicated!");
        return false;
      } else if (data === '1') {
        document.getElementById("frm").submit();
      }
    }
  })
})

Solution

  • To do what you require you should hook to the submit event of the form and call preventDefault() on the Event. You can then make your AJAX request to determine the state of data and then either manually resubmit the form, or do nothing if the submission should not be allowed.

    Here's an example of what the logic would look like:

    $("#frm").on('submit', e => {
      e.preventDefault();
    
      $.ajax({
        type: "POST",
        data: {
          q: $('#elm').val()
        },
        url: "getunique.php",
        success: function(data) {
          if (data === '0') {
            $("#elm").val("");
            alert("duplicated!");
          } else if (data === '1') {
            e.target.submit(); // resubmit form
          }
        }
      })
    })
    

    As an aside, you should review how your getunique.php is returning data. Returning a plain-text response is not good practice as it's very brittle, and will easily be broken. In addition, returning a string for a boolean output is not ideal.

    I would suggest you instead return JSON with a boolean flag that you can then interrogate to determine the action to take.