I have an AJAX form that only shows a captcha for the user when the form is submitted more than 2 times.
I saved these attempts in $_SESSION
with PHP, however as the form is sent via AJAX the captcha will only appear when the user refreshes the page even though he has submitted the form more than 2 times.
This happens because I'm not updating the headers I believe. How would I do this with AJAX? When sending form
is this data updated?
@Edit:
In my contact.php
I do the following to set the requisitions
if ($_SERVER['REQUEST_METHOD'] == 'POST') $_SESSION['attemptsSendEmail'] += 1;
if ($_SESSION['attemptsSendEmail'] >= 2) {
if(!isset($ret->captcha)){
http_response_code(401);
exit('Captcha errado, bloqueado pelo anti-spam');
}
if (isset($ret->captcha) && $ret->captcha !== $_SESSION['captcha']) {
http_response_code(401);
exit('Captcha errado, bloqueado pelo anti-spam');
}
}
And here the validation in Javascript
waghcwb.query('#contact-form').onsubmit = function(event) {
event.preventDefault();
var btn = waghcwb.query('#contact-form button[type="submit"]');
waghcwb.post('contact/contact.php', {
name: waghcwb.query('input[name="name"]').value,
email: waghcwb.query('input[name="email"]').value,
message: waghcwb.query('textarea[name="message"]').value,
captcha: (waghcwb.query('input[name="captcha"]')) ? waghcwb.query('input[name="captcha"]').value : null
}, function() {
btn.style.backgroundColor = '#34DB42';
btn.style.borderColor = '#34DB42';
btn.setAttribute('class', 'button success');
btn.innerHTML = '<img src="img/check.svg" alt="Enviado com sucesso" title="Enviado com sucesso">';
waghcwb.query('input[name="captcha"]').className = '';
if (waghcwb.query('#captchaImg')) waghcwb.query('#captchaImg').src = '/captcha/captcha.php?' + new Date().getTime();
waghcwb.query('input[name="name"]').value = '';
waghcwb.query('input[name="email"]').value = '';
waghcwb.query('textarea[name="message"]').value = '';
if (waghcwb.query('input[name="captcha"]')) waghcwb.query('input[name="captcha"]').value = '';
}, function() {
btn.style.backgroundColor = '#DB3434';
btn.style.borderColor = '#DB3434';
btn.setAttribute('class', 'button error');
btn.innerHTML = '<img src="img/times.svg" alt="Erro ao enviar os dados" title="Erro ao enviar os dados">';
},
function() {
var input_captcha = waghcwb.query('input[name="captcha"]'),
captcha = waghcwb.query('#captchaImg');
input_captcha.placeholder = 'O código de segurança não confere.';
input_captcha.className = 'error';
input_captcha.value = '';
if (captcha) captcha.src = '/captcha/captcha.php?' + new Date().getTime();
});
};