Lets create a simple registration form with HTML5 form field validation and PHP Captcha. On submit this form will validate captcha without page refresh and POST data using jQuery. So both captcha verification and save data to mysql database can be done without page load.

Registration Form


Generating an Image CAPTCHA

The following code will generate an alphanumeric captcha with custom font.
 
<?php
session_start();
function getRandomWord($len = 5) {
$word = array_merge(range('0', '9'), range('A', 'Z'));
shuffle($word);
return substr(implode($word), 0, $len);
}

$ranStr = getRandomWord();
$_SESSION["vercode"] = $ranStr;

$height = 35; //CAPTCHA image height
$width = 150; //CAPTCHA image width
$font_size = 24; //CAPTCHA Font size

$image_p = imagecreate($width, $height);
$graybg = imagecolorallocate($image_p, 245, 245, 245);
$textcolor = imagecolorallocate($image_p, 34, 34, 34);

imagefttext($image_p, $font_size, -2, 15, 26, $textcolor, 
'fonts/mono.ttf', $ranStr);
imagepng($image_p);
?>

You can save the above code in captcha.php and call the file in img src tag.
 
<img src="captcha.php" /><br>

On submit you can call your php file through jQuery to validate your captcha code and save data.
 

Validate captcha in jQuery without page load

$(document).ready(function(){
$('#register').submit(function() {

$.post("submit_form.php?"+$("#register").serialize(), { }, function(response){
if(response==1){
$(".imgcaptcha").attr("src","demo_captcha.php?_="+((new Date()).getTime()));
    clear_form();
    alert("Data Submitted Successfully.")
}else{
    alert("wrong captcha code!");
}
});
return false;
});

function clear_form(){
  $("#fname").val('');
  $("#lname").val('');
  $("#email").val('');
  $("#phone").val('');
  $("#username").val('');
  $("#password").val('');
  $("#cpassword").val('');
  $("#captcha").val('');
}

});

Validate captcha in PHP

<?php
session_start();
if(($_REQUEST['captcha'] == $_SESSION['vercode'])){
  $fname = mysql_real_escape_string($_REQUEST['fname']);
  $lname = mysql_real_escape_string($_REQUEST['lname']);
//Here you can write your sql insert statement. 
  echo 1;
}else{
  echo 0;
}
?>


Demo   Download File

Top