Как прикрутить ReCaptha, если на form уже висит action

249
02 августа 2017, 22:16

Есть попап плагин обратной связи, форме в котором уже присвоен экшн (отправка полей формы на email)

<div class="callback-form {$inline_container}">{$label}{$description}<form id="send"  class="clearfix callback-form-container" action="{$form_action}" method="POST"> //inputs <button id="" data-sitekey="" ...></button></from></div>

Прикрутил к форме recaptcha, пришлось изменить экшн с

$form_action = get_site_url() . '/?form_action=email';

на

$form_action = get_site_url() . '/captcha.php';

код reaptcha

<?php
require '1.php';
$recaptcha = $_POST['g-recaptcha-response'];
$object = new Recaptcha();
$response = $object->verifyResponse($recaptcha);
if(isset($response['success']) and $response['success'] != true) {
    exit("An Error Occured and Error code is :".$response['error-codes']);
}else {
}

Сейчас при отправке формы, естественно, открывается /captcha.php с текстом "Correct Recaptcha", на этом все заканчивается, email не уходит

Как мне сделать, чтобы после проверки капчи отправлялась форма, без переадресации на captcha.php

Помогите, пожалуйста.

Answer 1

валидация

jQuery(document).ready(function($) {
        $('.callback-form-container').submit(function() {
            var formInputs = $(this).find('.validate');
            var errors = '';
            $(formInputs).each(function() {
                if($.trim(this.value) == '') {
                    fieldLabel = $(this).parent().find('span.label-text').html();
                    errors += '- ' + fieldLabel + '\n';
                }
            });
            if(errors.length > 0) {
                alert('Пожалуйста, заполните следующие поля:\n\n' + errors);
                return false;
            }
            else
            {
                $('.submit-button').val('Пожалуйста, пододжите...');
                $('.submit-button').attr('disabled', 'disabled');
                return true             
            }           
            });         
        }); 
});

reCaptcha.php

if(isset($_POST['g-recaptcha-response'])) {
    $result = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=6(secret code)O&response=$_POST["g-recaptcha-response"]&remoteip=$_SERVER["REMOTE_ADDR"]'), TRUE);
    if($result['success'] == 1) {
        console.log("Ok");
    } else {
        grecaptcha.reset();
    }
}

ajax, который не получается правильно разместить:

    function onSubmit(token) {                      
        document.getElementById("send").submit();
    $.ajax({
        type: "POST",
        url: "/reCaptcha.php",
        data: f.serialize(),
        dataType: "json",      
    });
}
Answer 2

Примерно как-то так:

jQuery(document).ready(function($) {
    var form=$('.callback-form-container');
    form.submit(function() {
        var formInputs = $(this).find('.validate');
        var errors = '';
        $(formInputs).each(function() {
            if($.trim(this.value) == '') {
                fieldLabel = $(this).parent().find('span.label-text').html();
                errors += '- ' + fieldLabel + '\n';
            }
        });
        $.ajax({
           type: "POST",
           url: "/reCaptcha.php",
           data: form.serialize(),
           dataType: "json", 
           error:function(){
              //
           },
           success:function(result){
             if(errors.length > 0) {
                alert('Пожалуйста, заполните следующие поля:\n\n' + errors);
             }else{
                $('.submit-button').val('Пожалуйста, пододжите...');
                $('.submit-button').attr('disabled', 'disabled');
                //еще какие-то действия            
             }
           }     
        });
    }); 
});

Общая суть: Валидируем данные, затем посылаем ajax-запрос на каптчу, если все ОК, то отправляем данные дальше, если нет, то показываем ошибки.

Answer 3
jQuery(document).ready(function($) {
    var form=$('.callback-form-container');
    form.submit(function() {
        var formInputs = $(this).find('.validate');
        var errors = '';
        $(formInputs).each(function() {
            if($.trim(this.value) == '') {
                fieldLabel = $(this).parent().find('span.label-text').html();
                errors += '- ' + fieldLabel + '\n';
            }
        });
        $.ajax({
           type: "POST",
           url: "/reCaptcha.php",
           data: form.serialize(),
           dataType: "json", 
           CheckSend: function(){
                        $("#status").html("logging in...");
                    },
                    success: function(response){
                        $("#alert").html(response.text);
                        if(response.type=="success"){
                           //что добавить?            }
                    },
                    error: function(){
                        $("#alert").html("Failed.");           
           },
           success:function(result){
             if(errors.length > 0) {
                alert('Пожалуйста, заполните следующие поля:\n\n' + errors);
             }else{
                $('.submit-button').val('Пожалуйста, пододжите...');
                $('.submit-button').attr('disabled', 'disabled');
                //еще какие-то действия            
             }
           }     
        });
    }); 
});
READ ALSO
Правильная обработка переносов в Markdown

Правильная обработка переносов в Markdown

Столкнулся с проблемойПростейший сайт с текстовыми статьями, бэк на Phalcon PHP Framework (не суть), фронт ни на чём, отдельные JS наподобие jQuery и иже...

187
В telegram не передается значение

В telegram не передается значение

В первый раз пишу телеграм ботаУ него есть некоторые команды

177
загрузка и вывод фото из базы данных

загрузка и вывод фото из базы данных

Так у меня 2 файла addphp для upload-a а индекс для вывода

232
перенос на новую строку php

перенос на новую строку php

записываю в phpWord

266