0

ajaxを使用してポップアップメニューを使用してコメントボックスを表示するコメントフォームがあり、コメントを送信すると、コメントが適切な投稿に登録されます(ページを更新する必要はありません)。このフォームにキャプチャを追加します。

小さな乱数キャプチャを生成する次の JavaScript コードを実装してみました。

<p>

      <label for="code">Write code below > <span id="txtCaptchaDiv" style="color:#F00"></span><!-- this is where the script will place the generated code -->

      <input type="hidden" id="txtCaptcha" /></label><!-- this is where the script will place a copy of the code for validation: this is a hidden field -->

      <input type="text" name="txtInput" id="txtInput" size="30" />

</p>

上記の html は、生成されたキャプチャと、ユーザーがコードを入力するためのテキスト入力を表示するために使用されます。

以下は、コードを生成する JavaScript コードです -

<script type="text/javascript">
//Generates the captcha function    
    var a = Math.ceil(Math.random() * 9)+ '';
    var b = Math.ceil(Math.random() * 9)+ '';       
    var c = Math.ceil(Math.random() * 9)+ '';  
    var d = Math.ceil(Math.random() * 9)+ '';  
    var e = Math.ceil(Math.random() * 9)+ '';  

    var code = a + b + c + d + e;
    document.getElementById("txtCaptcha").value = code;
    document.getElementById("txtCaptchaDiv").innerHTML = code;  
</script>

次の JavaScript コードは、キャプチャの検証に使用されます -

<script type="text/javascript">
function checkform(theform){
    var why = "";

    if(theform.txtInput.value == ""){
        why += "- Security code should not be empty.\n";
    }
    if(theform.txtInput.value != ""){
        if(ValidCaptcha(theform.txtInput.value) == false){
            why += "- Security code did not match.\n";
        }
    }
    if(why != ""){
        alert(why);
        return false;
    }
}

// Validate the Entered input aganist the generated security code function   
function ValidCaptcha(){
    var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
    var str2 = removeSpaces(document.getElementById('txtInput').value);
    if (str1 == str2){
        return true;    
    }else{
        return false;
    }
}

// Remove the spaces from the entered and generated code
function removeSpaces(string){
    return string.split(' ').join('');
}

</script>

このコードは、コメント フォームと組み合わせない場合に適切に機能します。コメント フォームと組み合わせた場合、検証は行われません。

ajax ベースのコメント フォームの場合、送信ボタンは、適切な投稿に関連付けるコメントの送信時に非表示の入力変数を渡します。これは、私のコメント セクションの送信ボタン コードです。

<button type="submit" class="comment-submit btn submit" id="submitted" name="submitted" value="submitted"><?php _e( 'Submit', APP_TD ); ?></button>

<input  type='hidden' name='comment_post_ID' value='<?php echo $post->ID; ?>' id='comment_post_ID' />

したがって、基本的には、コメントフォームの送信ボタンで最初にコードでキャプチャ値をチェックし、適切な場合は ajax 機能のみを使用してコメントを送信したいと考えています。

4

1 に答える 1