Update headers with AJAX

Asked

Viewed 204 times

0

I have an AJAX form that only shows a captcha to the user when the form is sent more than 2 times.

I save those attempts on $_SESSION with PHP, but as the form is sent via AJAX captcha will only appear when the user refreshes the page even though he has sent the form more than 2 times.

This is because I’m not updating the headers I believe. How would I do this with AJAX? By sending the form that data be updated?

@Edit: In my contact.php I do the following to set the requests

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();
        });
};
  • Post what you have done in JS. If you count the attempts use the var to show the captcha.

  • 2

    You can increment the Sessions variable in PHP each time ajax calls it. Type $_SESSION['visitas']+=1; inside the PHP file that ajax calls

  • @Sergio, I already do this in PHP, the problem is that sending by Ajax to each request this is not updated on the page.

  • @Jader, I added the codes. If I just reload the form element with a new AJAX request the $_SESSION data is updated?

  • 1

    @waghcwb if everything is all right with cookies (which pass the Session ID) or the Session ID is passed correctly by the url (php usually does this automagically) should work yes...

1 answer

1


Place your captcha in a hidden div, and count in the JS the number of submissions via the form ajax. After sending, if the counter reaches 2, show the div with jquery or normal javascript, going from Hide to block mode. Then, when sending the form via js, just check if the counter is above 2 and test the captcha before sending the form.

EDITED: I don’t know if I could make a new answer... but anyway, I’m editing this one:

The way you did, it actually got easier even... because you’re already passing the captcha by the call of ajax..

So, before the

waghcwb.query('#contact-form').onsubmit = function(event) {

you will create a variable for your counter:

var contadorform = 0;

and will add within your shipment:

...
var btn = waghcwb.query('#contact-form button[type="submit"]');
contadorform = contadorform + 1; // ou contadorform ++;
...

and will also pass it as a parameter for your contact.php

...
name: waghcwb.query('input[name="name"]').value,
email: waghcwb.query('input[name="email"]').value,
message: waghcwb.query('textarea[name="message"]').value,
contador: contadorform,
...

And finally, in contact.php, you will test this counter variable:

if ($_POST['contador'] >= 2) {

Everything else will be on top of this variable, both in JS and PHP.

In case you have any questions left, just say that I comment to explain better.

  • Who denied and why?

  • Perhaps it was due to the lack of a more illustrative example. The way he answered was like a simple comment.

  • Illustrative example for illustrative example, he should have posted his source code. If not posted, it is understood that he can understand what is spoken, since he does not need help to fix the source code.

  • How do I write a good answer? "Being brief is acceptable, but more complete explanations are better." I didn’t deny it, I just informed a possible reason.

  • @Marcelogomes, I was away for a few days. But I wasn’t the one who denied her answer. I hadn’t even seen her yet! I’m putting the code to analysis.

  • @waghcwb edited the answer, showing with bits of the source code where the changes should be made. Since it is ajax, the return will not be able to update Session, so using a JS variable is more functional. Test by the JS variable and show the captcha field by validating only the counter in JS...

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.