Prevent PHP form submit depending on Ajax form response

I have a PHP form that is used for entering a membership number.

When the input field changes, an ajax call is fired to a. check that the card number is from a valid range of possible card numbers and b. check if the card has already been issued.

If both checks are satisfied then no error message are displayed and the user can submit the form.

If either check fails, a warning message is displayed (either card not valid, or card already issued), but the form can still be submitted.

I also use https://jqueryvalidation.org/ to validate the format of the field and other in the form.

I am looking for a way of making the submit button "disabled"  unless the 2 checks on the field are satisfied. This could be either via the https://jqueryvalidation.org/ or otherwise.

The relevant parts of the code are shown below

Thank you.

<form action'#' method='post' id='account-add'>";
Card No<br/>
<input type='text' name='cardno' id='cardno'/><div id='disp'></div>
<input type='hidden' name='postback' value='add'/>
<input type='submit' id='submit' value='Add' />
</form>
	
<!--jquery validation-->
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js?v=1"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js?v=1"></script>
<script>
$().ready(function() {
					$.validator.addMethod("cardno", function(value, element) {
							return this.optional(element) || /^xyz[0|1|9]\d{5}X$|^LYBLA[2|3|4|9]\d{6}$|^TMP\d{9}$/i.test(value);
					}, "Card Number is invalid. It should be xyz, 6 digits ending with X, or 7 digits");
$("#account-add").validate({
		rules: {
			cardno: {cardno:true,
							required:true},
		},
		messages: {
			cardno: "Card no must be in the format xyz followed by 6 digits ending in X, or 7 digits.",
		}
	});

});
</script>

<!--Ajax call-->
<script type="text/javascript">
$(document).ready(function(){
$("#cardno").change(function() {
var cardno = $('#cardno').val();
if(cardno==="")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "match-cardno.php",
data: "cardno="+ cardno + "&companyid=xyz",
success: function(html){
$("#disp").html(html);
}
});
return false;
}
});
});
</script>

Open in new window


match-cardno.php
<?php session_start();

include 'config.php';


if(isset($_POST['cardno'])){
$cardno=$_POST['cardno'];
$companyid=$_POST['companyid'];

//check card exists in list of possible cards
$sql="select cardno from tblcardpossibles where cardno =? and companyid=?";
$params=array($cardno, $companyid);
$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$result=sqlsrv_query($conn, $sql, $params, $options);
include "error.php";

$row_count = sqlsrv_num_rows($result);
if($row_count=='0'){
echo "<p class='error'>You have entered an invalid card number. Please check your entry. </p>";}


//Check if card has already been issued
$sql="select title, firstname, surname, postcode from tblcardsissued where cardno =? and companyid=?";
$params=array($cardno, $companyid);
$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$result=sqlsrv_query($conn, $sql, $params, $options);
include "error.php";

$row_count = sqlsrv_num_rows($result);
$row= sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC);

if($row_count<>0){
$title=$row['title'];
$firstname=$row['firstname'];
$surname=$row['surname'];
$postcode=$row['postcode'];
echo "<p class='error'>Card already issued to $title $firstname $surname, $postcode</p>";}
}

?>

Open in new window

rwlloyd71Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Scott Fell, EE MVEDeveloper & EE ModeratorCommented:
What you want to do is make submit button disabled on start, after each of the required fields are entered, use your ajax call to return either a yes or no value.  When both fields return yes, then enable the submit button.

Front end validation is good to help the user fix quick errors like not entering a valid date or leaving a field blank.  You still have to do the validation on the back end regardless.  For validating credit cards, I have always just left that to the back end and display any messages received from the processor.

In this case, I would simply submit the number, then on the back end first run it through your own database to make sure there is not a match.  If there is a match update your error information and send back to the user. If there is not a match, process the card number and get your validation from that service.  All of this can be done in one ajax call.  Then only use your jquery validation to disable the submit button once there are some numbers in the field.
0
rwlloyd71Author Commented:
Thanks Scott.

I think that I follow the login, but not too hot on javascript, so I'll give it a go, but I might come back to you if I get stuck.

Hope that it OK.
0
Scott Fell, EE MVEDeveloper & EE ModeratorCommented:
See if this example helps.  Enter anything and tab.  If you enter 25, then it will match just as if it found a number in your database and the button will remain disabled.  This is over simplified for demo.

http://jsbin.com/keqijuhowi/edit?html,output
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
 $( document ).ready(function() {
    
   // start off with button disabled
     $('#submit').prop('disabled', true);
   
   // After you enter the card, validate
     $('#cardno').on('blur',function(){
       
       // set variable cardno to value entered
       var cardno = $(this).val();
       
       // place the cardno variable through the valdidateCard function
       if(validateCard(cardno)){
         
         // if it does not equal 25 then enable the button
         $('#submit').prop('disabled', false);
         $('#msg').text('valid');
         
       } else {
         // if 25 then disable
         $('#submit').prop('disabled', true);
          $('#msg').text('number exists');
         
       }
     });
   
   
   
   // simulate finding a card
     function validateCard(number){
      if(number==25){
        return 0;
      } else {
        return 1;
      }
      
    }
    
   
  });
  </script>
</head>
<body>
  <input type="text" name="cardno" id="cardno"/>
  <input type='submit' id='submit' value='Add' />
  <div id="msg"></div>

</body>
</html>

Open in new window


Where I have $('#msg').text('valid'); you can submit the form data either via ajax or jquery submit   https://api.jquery.com/submit/
$('form#account-add').submit();
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
rwlloyd71Author Commented:
That's very kind of you. Thank you.

I'll give it a go.
0
Scott Fell, EE MVEDeveloper & EE ModeratorCommented:
You didn't have to close out the question.  I hope this helped you make sense of things.

For this, you really are only concerned with the front end (html/css/js).  Your backend code is only processing your ajax requests.

1) Use jqueryvalidation only to prevent potential bad data from being submitted

2) If you do  use the card already in use test via ajax in conjunction with jqueryvalidation, then make sure to also validate on form submit (don't trust any submitted data)

If you run into trouble, just post another question with your code or link to your example page.

Thanks!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.