I'm trying to make a custom captcha generator. In short, the server returns a URL of an image through AJAX and keeps in session storage an association with the image.
PHP:
add_action( 'wp_ajax_set_animal_captcha', 'set_animal_captcha' );
$capdir = get_template_directory_uri() . '/assets/captcha/';
$capmap = array ( 'cat' => $capdir . 'Captcha_Cat.png',
'dog' => $capdir . 'Captcha_Dog.png',
'fish' => $capdir . 'Captcha_Fish.png' );
function set_animal_captcha ( )
{
// returns image url of random animal and stores in session storage
// a reference to that animal
$randAnimal = array_rand($capmap,1);
$_SESSION['randAnimal'] = $randAnimal;
die(json_encode($capmap[$randAnimal]));
}
JS:
function capHandler ( imgid )
{
// imgid: id of the image
this.imgid = imgid;
this.formData = new FormData();
this.formData.append('action', 'set_animal_captcha');
this.set = function ( )
{
$.ajax({
url: ajaxurl,
type: 'POST',
async: false,
success: function ( animalUrl ) { alert(animalUrl); },
error: function ( ) { alert("Error in getting captcha image") },
cache: false,
contentType: false,
processData: false
});
}
}
My problem is that it's alerting
0
and I can't figure out why. Because I know the success
function is being called, there must be something wrong with the PHP.