Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit or not a form using jquery and javascript

i have a form like:

<form name="form" id="form" action="sub.php" onsubmit="return checkField();">
.
.
.
</form>

in head i have:

<script>
   function checkField(){
      var fieldToCheck = $('#field').val();
      $.post("checkField.php",{field:fieldTocheck},function(msg)){
         return msg=='ok';
      }
   }
</script>

the problem is that form will submit always.. i know that the return inside $.post is for function of success and not for function checkField() .. so what can i do? can someone help me? Thanks!!

like image 615
Jayyrus Avatar asked Feb 24 '26 12:02

Jayyrus


1 Answers

1st, prevent the submit event:

$('#form').submit(function(event) {
event.preventDefault();
}

2nd, if all ok, proceed with submission

   function checkField(){
      var fieldToCheck = $('#field').val();
      $.post("checkField.php",{field:fieldTocheck},function(msg)){
         $('#form').submit();
      }
   }
like image 157
Ivan Buttinoni Avatar answered Feb 26 '26 00:02

Ivan Buttinoni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!