2017-01-11 4 views
2
<form action="#" method="post" id="contactMsg"> 
    <div class="row"> 
     <div class="col-md-4"> 
      <input name="name" id="name" required="required" type="text" placeholder="Name"> 
     </div> 
     <div class="col-md-4"> 
      <input name="email" id="email" required="required" type="text" placeholder="Email"> 
     </div> 
     <div class="col-md-4"> 
      <input name="subject" id="subject" required="required" type="text" placeholder="Subject"> 
     </div> 
     <div class="col-md-12"> 
      <textarea name="comments" id="comment" required="required" cols="10" rows="10" placeholder="Comments"></textarea> 
     </div> 
     <div class="col-md-12"> 
      <input name="comment" id="ContactNow" type="submit" value="Submit"> 
     </div> 
    </div> 
</form> 

// Здесь код AjaxКак использовать captcha перед отправкой формы. в HTML Javascript

var formData = new FormData($("#contactMsg")[0]); 

$.ajax({ 
    url: 'contactMsg.php', 
    data:formData, 
    cache: false, 
    contentType:false, 
    processData:false, 
    type: 'post', 
    success: function(response) { 
     $("#contactMsg")[0].reset(); 
     $("#SucessMsg").fadeIn('slow').delay(3000).fadeOut('slow'); 
    } 
}); 

Я никогда не использую капчу. Я действительно не знаю об этом. пожалуйста, у кого-нибудь есть идея, чем показать мне, я хочу добавить captcha, а не проверять ее перед вызовом ajax. заранее спасибо

+0

Вы можете использовать простой математический Capcha или Capcha изображения. какой из них вы хотели? –

+0

простая математика capcha –

+0

Эй, см. Пример. –

ответ

0

См простой пример:

$(document).ready(function(){ 
 
    var a = (Math.ceil(Math.random()*9))+1; 
 
\t var b = (Math.ceil(Math.random()*9))+1; 
 
\t var queryText = a+" + "+b+"="; 
 
\t document.getElementById('queryString').innerHTML=queryText; 
 
\t var result = parseInt(a)+parseInt(b); 
 
\t document.getElementById('actualResult').value=result; 
 
}); 
 
\t \t \t 
 
function _validate(){ 
 
    if(document.getElementById('actualResult').value == document.getElementById('result').value){ 
 
\t \t alert("matched"); 
 
\t }else{ 
 
\t  alert("not matched"); 
 
\t } 
 
\t \t \t 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<body> 
 
    <form action="#" method="post" id="contactMsg"> 
 
    \t <div class="row"> 
 
    \t <div class="col-md-4"> 
 
    \t \t <input name="name" id="name" required="required" type="text" placeholder="Name"> 
 
    \t </div> 
 
    \t <div class="col-md-4"> 
 
    \t \t <input name="email" id="email" required="required" type="text" placeholder="Email"> 
 
    \t </div> 
 
    \t <div class="col-md-4"> 
 
    \t \t <input name="subject" id="subject" required="required" type="text" placeholder="Subject"> 
 
    \t </div> 
 
    \t <div class="col-md-12"> 
 
    \t \t <textarea name="comments" id="comment" required="required" cols="10" rows="10" placeholder="Comments"></textarea> 
 
    \t </div> 
 
    \t <div class="col-md-12"> 
 
    \t \t <label id="queryString"></label> 
 
    \t \t <input type="text" value="" id="result"/> 
 
    \t </div> 
 
    \t <input type="hidden" id="actualResult"/> 
 
    \t <div class="col-md-12"> 
 
    \t \t <input name="comment" id="ContactNow" type="button" value="Submit" onclick="_validate();"> 
 
    \t </div> 
 
    </div> 
 
    </form> 
 
</body>

Объяснение: При загрузке страницы, то мы генерируем случайное число и сделать строку запроса и сделать фактический результат в скрытый поле. когда пользователь отправляет, мы проверили вход пользователя с этим скрытым полем input.if, тогда мы прошли, а если не заблокировали.

+0

Я думаю, что вы не должны хранить результат captcha на странице ... – Fif

+0

@Fif Почему мы не должны хранить результат на странице? Если каждая обновленная страница способна генерировать новый код, то в чем проблема? Расскажи мне подробности. –

+0

Целевая точка captcha заключается в предотвращении отправки роботов. Если вы предоставили результат captcha непосредственно на странице, тогда робот может легко прочитать его и отправить его остальной форме. – Fif

0

Вы можете использовать этот код, его работу тонкого you may download captcha images from given link

var val=[];   
 
val.push("VQ7W3");  /** push value in this array */ 
 
val.push("A1234");  /** To maintain image order here */ 
 
val.push("A32BD"); /** if first image 0_capt.jpeg contains value VQ7W3 so push this value into zero(0) index of array */ 
 
val.push("LD673"); 
 
val.push("PQ78V"); 
 
val.push("MX81W"); 
 
var x; 
 
/**This below method generate random number from 0-5 
 
* name of image starts with that number will set on 
 
* captcha location 
 
*/ 
 
function myFunction() { 
 
    x = Math.floor(Math.random() * 6);  // here 6 stand for how many images you are using return 0-6 number. 
 
\t $("#imgCaptchaPlace").html("<img id='abc' src='captcha_images/"+x+"_cpt'/><br>"+val[x]) ; 
 
} 
 
myFunction(); 
 
/** 
 
* This below method will call on change of input fields where user enter 
 
* captcha code value 
 
*/ 
 
function chaeckCpatch(id) 
 
{ 
 
\t \t if($("#"+id).val()==val[x]) 
 
\t \t { 
 
\t \t \t \t alert("match"); 
 
\t \t } 
 
\t \t else 
 
\t \t { 
 
\t \t \t alert("No match"); 
 
\t \t } 
 
\t 
 
}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
 
<html> 
 
<head> 
 
</head> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
<body> 
 
<!-- below div use to display captcha image --> 
 
<div id="imgCaptchaPlace"></div> 
 

 
<!-- below textfield where user enter captcha value --> 
 
<input type="text" id="captchaText" onchange="chaeckCpatch(this.id);"/> 
 

 
<!-- include this JS file --> 
 
<script src="captchByAarif.js" type="text/javascript"></script> 
 
</body> 
 
</html>

Смежные вопросы