发布前验证

I have this little code (part of my registration code) :

<?php 
 if (@$_POST['Submit'] == 'Register'){

     if (strcmp(md5($_POST['user_code']),$_SESSION['ckey']))
    { 
         die("Invalid code entered. Please enter the correct code as shown in the Image");
    } 
 } 
 ?> 

<form name="form1" id="signupForm" method="post" action="register.php" style="padding:5px;">
<div class="reg_left">Security code:</div>
<div class="reg_right"><input name="user_code" type="text" size="10"> <img src="pngimg.php" align="middle" width="100" height="40"></div>
<div><input type="submit" name="Submit" class="submit" value="<?php echo $gomb_reg;?>"></div>
</form>

Unfortunately this is check if code is valid after post the form data. I would like to check before posting.

So I think I must use jQuery validation plugin (btw I use jQuery to validate the other fields like email, user, password). But as I'm not an expert in jQuery, I need help to write that php code above in jQuery.

Thank you.

I believe the basic jist would be:

  • Hook a function to the submit element
  • That JS function sends the user_code value to PHP script
  • The PHP script checks the value and and outputs (returns) a bool (or json)
  • The JS function allows the post if a good value is returned

(Note: Since the jQuery AJAX function do not stop the execution of the script, you'll have to stop the form from submitting, then submit the form in the AJAX callback.)

Look at the jQuery docs for .post or .getJSON, use those function to sent the 'user_code' to be checked.

You can keep most of your php code the same, but you'll want to check for the request header type.

I'm pretty sure jQuery sends the X-Requested-With : XMLHttpRequest but I'm not entirely sure and its late, so to somewhat modify your php script it would look something like this

if (@$_POST['submit'] == 'Register') {
     if (strcmp(md5($_POST['user_code']),$_SESSION['ckey']))
     { 
           // check if the request was from an ajax call
          if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'){

           //if it is an ajax request we need to send back a json encoded array
             $response = array('success' => 'true', 'message' => 'Invalid code';

              // now we encode the array and echo it back
              echo json_encode($response);

              // exit the script for safety
              exit();
          } else {
           // if the request wasn't ajax the respond business as usual
           die("Invalid code entered. Please enter the correct code as shown in the Image");
         } 
    } 
} 

As for the jQuery code it would probably look something like this:

$(document).ready(function(){

    // this creates an event handler on the form submit
     $('#signUpForm').submit(function(){

           // you'll need to give your user_code input an id of user_code
           var user_code = $('#user_code').val(); 

           // I like to use the jQuery $.ajax method since it gives you more controll
          $.ajax({
                // send a post request

                type : 'POST',

                // the url you'll be sending the request too

                url: 'register.php',

                // the type of data you're expecting back
                // i prefer json since its easier to work with for me

                dataType : 'json',

                // the data you want to send which would be your user_code data 
                // send this in a name/value pair

                data : 'user_code=' + user_code + '&submit=Register',

                // the success function is called when the ajax call has been
                // completed, not whether the user_code matches the $_SESSION['ckey']
                // the data variable will contain your json data
                success : function(data, textStatus){

                   // since we json encoded the php array it will
                  // look something like this 
                  //{ success : 'true', message : 'incorrect code'}

                       if(data.success == 'true'){
                           // what you plan on doing if the code is correct
                           alert(data.message);
                       } else {
                           // what you do if the code is incorrect
                           alert(data.message);
                       }
                }
           });

         // stop the form from submitting
         return false;
     });
});

I think that should just about do it. the $.ajax method has a few other call back functions such as onError, complete and similar messages that are worth looking into here. The $.ajax method is a little daunting at first, but after using it a few times, I now prefer it over the other ajax methods they have ($.load,$.get, $.getJSON, or $.post)