I need some help, as I can't reload a captcha image in my form, if the writing over the image is not very clear or simple to read, as it can happens sometimes.
I read a lot about that, here and around in the internet but my problem is different from what most people seem to have to face. In fact I create the captcha image in a page called - captcha.php - and then in another page called - contacts.php - I create the writing for the image and a casual unique string that I pass to the captcha.php file, as I don't want to use the sessions or cookies, but I use instead a database with a table called - validation. Translating all this in PHP, the captcha.php has this code to retrieve the string:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try
{
$stmt = $pdo->prepare("SELECT * FROM validation WHERE url_key = ? AND expire_date > NOW()");
$stmt->execute(array($_GET['token']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{
echo "Error!: " . $e->getMessage() . "<br />";
die();
}
etc.....
and then my contacts.php has this:
$url_key = sha1(uniqid(rand(), true));
$captcha = random_string(4);
try
{
$stmt = $pdo->prepare("INSERT INTO validation (id_validation, url_key, captcha, expire_date) VALUES ('', ?, ?, DATE_ADD(NOW(), INTERVAL 5 MINUTE))");
$stmt->execute(array($url_key, $captcha));
}
catch(PDOException $e)
{
echo "Error!: " . $e->getMessage() . "<br />";
die();
}
Now I do need, of course, to refresh just my image and not the entire contacts.php page. I know you can do that with Ajax, but I've got no good knowledge about that.
My contacts.php has the tag img to show the reader the captcha:
<img src="captcha.php?token=<?php echo $url_key; ?>" alt="" />
I tried to change it this way:
<img src="captcha.php?token=<?php echo $url_key; ?>" id="captcha" />
<a href="#" onClick="return changeCaptcha('captcha')">Reload the image</a>
and then in my head section, I put this Javascript code:
function changeCaptcha()
{
document.getElementById('captcha').src = 'captcha.php' +
Math.floor(Math.random()*100);
}
but it doesn't work at all. If I click on the link the captcha disappears completely.
I tried then to change this:
<img src="captcha.php?token=<?php echo $url_key; ?>" id="captcha" />
<a href="#" onClick="return reloadImg('captcha');">Reload the image</a>
and then with a new Javascript file, that's:
function reloadImg(id) {
var obj = document.getElementById(id);
var src = obj.src;
var pos = src.indexOf('?');
if (pos >= 0) {
src = src.substr(0, pos);
}
var date = new Date();
obj.src = src + '?v=' + date.getTime();
return false;
}
but it doesn't work even this way. The problem is in the - php echo $url_key; - as I don't know how to treat this. I can't do this for example:
function changeCaptcha()
{
document.getElementById('captcha').src = 'captcha.php?token=<?php echo $url_key; ?>' +
Math.floor(Math.random()*100);
}
as it's wrong again.
Do you have some ideas? Thank you in advance. Bye.