hi everyone i am trying to get validate captcha on my form but i would like validation to take place on the form without a change of state.

currently the page refreshes to display the error message and the page loses all form values and i can understand that this can be frustrating to users who have to retype the information.

how can i get the error message to display right below the captcha image area? this way the user can make the necessary corrections to their mistake without re-entering everything.

<?php session_start(); 
include_once ("resources/Connections/kite.php");
include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();
?>

<div class="c13">
  <table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td width="69%" align="center"><p class="c6">New Account</p>
        <?php
$username = mysql_real_escape_string($_POST['username']);
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$password = mysql_real_escape_string($_POST['password2']);

        //check if the form has been submitted

if(isset($_POST['submit'])){

    if ($securimage->check($_POST['captcha_code']) == false) {
  // the code was incorrect
  // you should handle the error so that the form processor doesn't continue

  // or you can use the following code if there is no validation or you do not know how
  echo "The security code entered was incorrect.<br /><br />";
  echo "Please go <a href='javascript:history.go(-1)'>back</a> and try again.";
}

else

    //success

    echo '<p class="c7">Thanks for signing up. We have just sent you an email at <b>'.$email.'</b>. Please click on the confirmation link within this message to complete registration.<br><img src="resources/img/spacer.gif" alt="" width="1" height="20"><br><span class="c12">
                          <input name="" type="button" class="c11" value="Register" onClick="location.href=\'main.php\'"/>
                    </span><br><img src="resources/img/spacer.gif" alt="" width="1" height="15"></p></div>';
    include_once ("resources/php/footer.php");      
exit;
}
?>
        <p class="c7">Just enter your details to get started</p>
        <div class="c10">
          <form action="<?php echo $PHP_SELF;?>" method="post" id="register" name="register">
            <table width="100%" border="0" cellpadding="0" cellspacing="">
              <tr>
                <td colspan="3" class="c8" height="25px" valign="bottom">Username</td>
              </tr>
              <tr>
                <td width="46%"></td>
                <td width="46%"></td>
                <td width="54%" class="c8"></td>
              </tr>
              <tr>
                <td colspan="3" class="c8"><span id="sprytextfield2">
                  <input name="username" type="text" class="required"/>
                  <span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldMaxCharsMsg">Exceeded maximum number of characters.</span></span></td>
              </tr>
              <tr>
                <td colspan="3" class="c8" height="25px" valign="bottom">Email</td>
              </tr>
              <tr>
                <td></td>
                <td></td>
                <td class="c8"></td>
              </tr>
              <tr>
                <td colspan="3" class="c8"><span id="sprytextfield3">
                  <input name="email" type="text" class="required"/>
                  <span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldMaxCharsMsg">Exceeded maximum number of characters.</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span></td>
              </tr>
              <tr>
                <td></td>
                <td></td>
              </tr>
              <tr>
                <td colspan="3" class="c8" height="25px" valign="bottom">Password (minimum of 8 characters)</td>
              </tr>
              <tr>
                <td></td>
                <td></td>
                <td class="c8"></td>
              </tr>
              <tr>
                <td colspan="3" class="c8"><span id="sprytextfield4">
                  <input name="password" type="password" class="required" id="password"/>
                  <span class="textfieldRequiredMsg">A value is required.</span><span class="textfieldMinCharsMsg">Minimum number of characters not met.</span><span class="textfieldMaxCharsMsg">Exceeded maximum number of characters.</span></span></td>
              </tr>
              <tr>
                <td colspan="3" class="c8" height="25px" valign="bottom">Confirm Password</td>
              </tr>
              <tr>
                <td></td>
                <td></td>
                <td class="c8"></td>
              </tr>
              <tr>
                <td colspan="3" class="c8"><span id="spryconfirm1">
                  <input name="password2" type="password" class="required"/>
                  <span class="confirmRequiredMsg">A value is required.</span><span class="confirmInvalidMsg">The values don't match.</span></span></td>
              </tr>
              <tr>
                <td colspan="3" class="c8" height="25px" valign="bottom">Enter Code</td>
              </tr>
              <tr>
                <td colspan="3" class="c8"><img id="captcha" src="resources/securimage/securimage_show.php" alt="CAPTCHA Image" />&nbsp; </td>
              </tr>
              <tr>
                <td colspan="3" class="c8"><input type="text" name="captcha_code" size="10" maxlength="6" />
                  <a href="#" onclick="document.getElementById('captcha').src = 'resources/securimage/securimage_show.php?' + Math.random(); return false">Swap image</a></td>
              </tr>
              <tr>
                <td colspan="3" class="c8"><span class="c12"><img src="resources/img/spacer.gif" width="1" height="40" alt="" /></span></td>
              </tr>
              <tr>
                <td colspan="3" class="c8"><span class="c12">
                  <input name="submit" type="submit" class="c11" value="Continue"/>
                  </span></td>
              </tr>
            </table>
          </form>
        </div>
        <br /></td>
      <td width="31%" valign="middle" align="center">&nbsp;</td>
    </tr>
  </table>
</div>

Dani AI

Generated

— the easiest, most user-friendly fix is to validate the CAPTCHA without doing a full page reload. pointed you in the right direction (either repopulate values server-side or use AJAX). Below is a compact, practical AJAX workflow and some safety/UX notes so the form keeps its data and shows the error inline under the image.

Client-side: intercept the form submit, POST just the captcha value to a small validation endpoint, show the error in a DOM node under the image if invalid, otherwise continue with the real submit.

document.getElementById('register').addEventListener('submit', function(e){
  e.preventDefault();
  const form = this;
  const code = form.querySelector('[name="captcha_code"]').value;
  fetch('resources/securimage/validate_captcha.php', {
    method: 'POST',
    credentials: 'same-origin',
    headers: { 'Accept': 'application/json' },
    body: new URLSearchParams({ captcha: code })
  })
  .then(r => r.json())
  .then(res => {
    let msg = document.getElementById('captchaError');
    if (!msg) { msg = document.createElement('div'); msg.id = 'captchaError'; form.querySelector('#captcha').parentNode.appendChild(msg); }
    if (!res.valid) {
      msg.textContent = res.msg || 'Incorrect code';
      document.getElementById('captcha').src = 'resources/securimage/securimage_show.php?' + Date.now();
    } else {
      form.submit();
    }
  }).catch(err => console.error(err));
});

Server-side endpoint: start the session, require Securimage, check the code and return JSON. Keep the handler tiny and return a boolean + message so the JS can update only the captcha area.

Security & UX notes

  • Always perform the final CAPTCHA check on the server (AJAX is only a UX improvement).
  • Ensure the AJAX call sends cookies (see credentials: "same-origin") so Securimage can read the session.
  • Do not repopulate password fields automatically for security; if you must repopulate text fields, escape with htmlspecialchars.
  • After a failed attempt refresh the captcha image to avoid replay.
  • Replace deprecated mysql_* calls with PDO/MySQLi and use password_hash for passwords.

This approach preserves the whole form on-screen, shows the error exactly where you want it, and keeps server-side validation intact.

You could either echo back all values (for example:

<input name="username" type="text" class="required" value="<?php echo $_POST['username']; ?>" />

), or you could move the validating to a seperate php file and call that with ajax.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.