Submitting an HTML form to a PHP file with JS validation

I’m sending data via an HTML form to a PHP file for it to be inserted into a DB with SQL script,
The same form is validated with JavaScript functions.

Each of the two works as expected separately,
but when used together – <form method="POST" action="myPHPFile.php" onsubmit="validationFunc(event)">
only the validation function works, and the page doesn’t get redirected to the PHP file.

When removing the JS (leaving only <form method="POST" action="myPHPFile.php">) – the data from the form is submitted properly and the page is redirected to the PHP file as expected.

I need to have some JS function to stop if the input is invalid,
and another to continue and send the input data to the PHP file if it’s valid.

Example code:

function isInputChars(evt) {
  let ch = String.fromCharCode(evt.which);
  if (!(/[a-z,A-Z,-]/.test(ch))) {
    alert("Please only enter only characters")
    evt.preventDefault();
  }
}

function validateForm(event) {
  event.preventDefault();

  var validateFormInputs = [];
  var inputLength;

  StringInput = document.getElementById("city");
  StringInput = StringInput.value;
  inputLength = StringInput.length;
  if (inputLength < 2) {
    alert("City: Please enter at least 2 Characters")
    validateFormInputs.push(false);
  } else {
    validateFormInputs.push(true);
  }

  StringInput = document.getElementById("street");
  StringInput = StringInput.value;
  inputLength = StringInput.length;
  if (inputLength < 2) {
    alert("Street: Please enter at least 2 Characters")
    validateFormInputs.push(false);
  } else {
    validateFormInputs.push(true);
  }

  var x;
  for (var i = 0; i < 2; i++) {
    if (validateFormInputs[i] === false) {
      x = false;
      break;
    } else {
      x = true;
    }
  }

  if (x == true) {
    console.log("Data is sent to DB")
    someFunctionToContinueSendingTheDate();
  } else {
    console.log("Data is INVALID")
    someFunctionToStop();
  }
}
<form name="myForm" method="POST" action="sendItem.php" onsubmit="validateForm(event)">
  <input id="city" name="city" type="text" class="form-control" onkeypress="isInputChars(event)" required>
  <input id="street" name="street" type="text" class="form-control" onkeypress="isInputChars(event)" required>
  <input type="submit" class="btn btn-primary btn-lg" value="Publish">
</form>

I’d be happy for some help with:

  1. How to redirect the input data to the PHP file (without removing the JS validation)
  2. How to implement the JS functions to send the data to the PHP/cancel.

Thank you!

41 thoughts on “Submitting an HTML form to a PHP file with JS validation”

Leave a Comment