captcha icon indicating copy to clipboard operation
captcha copied to clipboard

PlainJS: Validation fails after refresh image in Laravel 9

Open Dhermann27 opened this issue 3 years ago • 0 comments

Submits successfully on first load but when I use the refresh image function the validation fails ("no match"). Any plans for documentation additions for this feature?

page.blade.php

...
<span id="captchaimg">{!! captcha_img() !!}</span>
<button type="button" id="refreshcaptcha" class="btn btn-success"><i class="fas fa-sync-alt"></i></button>
<input id="captcha" name=" class="form-control mt-2 @error('captcha') is-invalid @enderror"/>
...

    <script type="text/javascript">
        function addEvent(el, type, handler) {
            if (el.attachEvent) el.attachEvent('on' + type, handler); else el.addEventListener(type, handler);
        }

        function getAjax(url, success) {
            var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
            xhr.open('GET', url);
            xhr.onreadystatechange = function () {
                if (xhr.readyState > 3 && xhr.status === 200) success(JSON.parse(xhr.responseText));
            };
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.send();
            return xhr;
        }

        var refreshCap = function () {
            getAjax('/refreshcaptcha', function (data) {
                document.getElementById('captchaimg').innerHTML = data.captcha;
            })
        }

        addEvent(document.getElementById('refreshcaptcha'), 'click', refreshCap);
    </script>

PageController.php

...
        $this->validate($request, [
            ...
            'captcha' => 'required|captcha'
        ], $messages);
...
    public function refreshCaptcha()
    {
        return response()->json(['captcha' => captcha_img()]);
    }

Do I need to do something special to pass the new key? I don't understand what the documentation means by session/stateless.

Cheers,

Dan

Dhermann27 avatar May 08 '22 16:05 Dhermann27