2

I have a form which i validate via php. this is how i do it:(example is for one 1 field)

elseif (ctype_alpha($firstname) != true)
     {

        $err_alpha_firstname =  "First Name cannot contain numbers";
     }

If in case the user does use an alpha numeric firstname, i display the error as :

<p><input type="text" class="span2" maxlength = "20" name="firstname" required id="firstname" placeholder="First Name"></p>
              <?php if (isset($err_alpha_firstname)) {echo $err_alpha_firstname;}?>

It all works fine. however since this validation is server side via php, inorder for the errors to show up, i have to submit the form, which then reloads( since the form submits to the page itself) and then the errors are displayed. Now I want those errors which are stored in a php variable ex:$err_alpha_firstname , to be displayed instantaneously via javascript or ajax (i dont know anything about either of the languages so pardon me please). Is there a simple script that would let me display those errors on the fly? I know php is server side and javascript is client side so there might be an issue.

html file:

<html lang="en">

  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="../../docs-assets/ico/favicon.png">

    <title>Fantasy Football</title>

    <!-- Bootstrap core CSS -->
    <link href="bootstrap/css/bootstrap.css" rel="stylesheet">
    <link href="bootstrap/css/jumbo.css" rel="stylesheet">
    <!-- Custom styles for this template -->
    <link href="jumbotron.css" rel="stylesheet">


  </head>

  <body>

    <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="#">Fantasy Football</a>
        </div>
        <div class="navbar-collapse collapse">
          <form class="navbar-form navbar-right" method="post" action="checkuser.php" name="check_form">
            <div class="form-group">
              <input type="text" placeholder="Username" name ="username" id="username" class="form-control">
            </div>
            <div class="form-group">
              <input type="password" placeholder="Password" name="password" id="password" class="form-control">
            </div>
            <input type="hidden" name="action" value="submit" />
              <button type="submit" class="btn btn-success">Sign in</button>
            <a href="#">Forgot Password?</a>
          </form>
        </div>
      </div>
    </div>


    <div class="jumbotron">
      <div class="container">
        <h1>Fantasy Football</h1>
        <p>Bring out the football manager in you!</p>
        <p>&nbsp;</p>
        <p>&nbsp;</p>
        <p>&nbsp;</p>
        <p>&nbsp;</p>
        <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Register &raquo;
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">New User Registration</h4>
      </div>
      <div class="modal-body">
       <form class="form-inline" method="post" action="<?php echo $_SERVER['PHP_SELF']?>" name="login_form">
        <span id="formerror" class="error"></span>
              <p><input type="text" class="span2" maxlength = "20" name="firstname" required id="firstname" placeholder="First Name"></p>
              <?php if (isset($err_alpha_firstname)) {echo $err_alpha_firstname;}?>
              <p><input type="text" class="span2" maxlength = "20" name="lastname" required id="lastame" placeholder="Last Name"></p>
              <?php if (isset($err_alpha_lastname)) {echo $err_alpha_lastname;}?>
              <p><input type="text" class="span2" maxlength = "20" name="username" required id="username" placeholder="Username"></p>
              <?php if (isset($err_ln_username)) {echo $err_ln_username;}?>
              <?php if (isset($err_empty_username)) {echo $err_empty_username;}?>
              <?php if (isset($err_alnum_username)) {echo $err_alnum_username;}?>
              <?php if (isset($err_unp)) {echo $err_unp;}?>
              <p class="help-block" style="font-size:12px"> Username should be between 4-20 characters long.</p>
              <p><input type="password" class="span2" name="password" placeholder="Password"></p>
              <?php if (isset($err_unp)) {echo $err_unp;}?>
              <?php if (isset($err_ln_password)) {echo $err_ln_password;}?>
              <?php if (isset($err_alnum_password)) {echo $err_alnum_password;}?>
              <p class="help-block" style="font-size:12px"> Password must be between 4-20 characters long. Must be alpha-numeric</p>
              <p><input type="password" class="span2" name="password_conf" placeholder="Re - Enter Password"></p>
              <?php if (isset($err_passwordconf)) {echo $err_passwordconf;}?>
              <p><input type="email" class="span4" name="emailid" required id="emailid" placeholder="Email ID"></p>
              <p><input type="text" class="span2" name="team_name" required id="team_name" placeholder="Team name"></p>
              <p class="help-block" style="font-size:12px"> Select your Unique team name.</p>
              <p>
                  <select class="secret_question">
                    <option>Select one of the below ....</option>
                     <option value ="0">The name of the city where you were born</option>
                     <option value ="1">The name of your first pet</option>
                     <option value ="2">What is your mother's maiden name</option>
                  </select>
                </p>
                <p><input type="text" class="span2" name="secret_answer" required id="secret_answer" placeholder="Secret Answer"></p>
                <p><input type="hidden" value="submit" /><br />
              <button type="submit" name="action" value = "submit" class="btn btn-primary">Register</button></p>
            </form>
      </div>
      <div class="modal-footer">

      </div>
    </div>
  </div>
</div>
      </div>
    </div>

    <div class="container">

      <div class="row">
        <div class="col-md-4">
          <h2>Rules</h2>
          <p>Rules of the Game </p>
          <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p>
        </div>
        <div class="col-md-4">
          <h2>Meet The Developers</h2>
          <p>Everyones name get mentioned here </p>
          <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p>
       </div>
        <div class="col-md-4">
          <h2>Contact Us</h2>
          <p>have an issue with the game. Click here to contact us.</p>
          <p><a class="btn btn-default" href="#" role="button">View details &raquo;</a></p>
        </div>
      </div>

      <hr>

      <footer>
        <p>&copy; B561 Project Fall 2013</p>
      </footer>
    </div> 


    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="bootstrap/js/bootstrap.min.js"></script>
    <?php include('newuseradd.php');?>
  </body>
</html>
7
  • Could you use session cookies? Or set the header location to login.php?errid=222 if ctype validates to false. You can then fetch those using the $_GET global. Commented Dec 3, 2013 at 0:08
  • something like this - // if( $_POST['form_token'] != $_SESSION['form_token']) // { // echo = 'Invalid form submission'; // } Commented Dec 3, 2013 at 0:09
  • With jquery, ajax is clear and easy. Commented Dec 3, 2013 at 0:10
  • could you give me a sample code to work around / understand? Commented Dec 3, 2013 at 0:11
  • Use the JQuery Post method api.jquery.com/jQuery.post to send data to your php file. Echo the response. Then display the received data back onto the page. It's all in the docs. No refresh is required. Commented Dec 3, 2013 at 0:13

2 Answers 2

2

You could either use straight JavaScript or AJAX to PHP. I'm going to show you the straight JS method.

You'd do something like this for each input.

 var hint = $("#fname-hint");
 var fname = $("#firstname");

fname.on("change", function(){
    if (!this.value.match(/\d+/g)) { // dosen't contain numbers
       hint.html("");
       fname.removeClass("error");
    }
    else {
       fname.addClass("error");
       hint.html("Your name can't contain numbers!");
    }
});

Now when the form is submitted, make sure there are no errors:

var form = $("#form");

form.submit(function(e) {
    var inputs = form.children("input");

    inputs.each(function(){
        var input = $(this);

        if (!input.hasClass("error")) {
            alert("Errors in form!");
            input.select();
            e.preventDefault();
            break;
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

I use the jQuery $.post() function and return json from my php code:

function fail ($message){
    die(json_encode(array('status'=>'fail', 'message'=>$message)));
}

function success ($message){
    die(json_encode(array('status'=>'success', 'message'=>$message)));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.