简体   繁体   中英

jQuery ajax validate captcha

i have a problem when posting a captcha to validate by php. I send the captcha_value string to the captcha_check.php and I don't know how to retrieve the returned value 'true' or 'false'

$("#myForm").submit(function() {
$.ajax({
       type: "POST",
       url: '/captcha_check.php',
       data: captcha_value
       success: function(data) {
          **?WHAT TO DO HERE? how to get true or false**
       }
});

captcha_check.php
<?php   

if ($_POST['captcha'] == $_SESSION['captcha'])
echo 'true';
else
echo 'false';
?>

I set header to output as xml.

captcha_check.php

<?php   
header('Content-Type:text/xml');//needed to output as xml(that is my choice)
echo "<root><message>";
if ($_POST['captcha'] == $_SESSION['captcha'])
echo 'true';
else
echo 'false';
echo "</message></root>";
?>

$("#myForm").submit(function() {
$.ajax({
       type: "POST",
       url: '/captcha_check.php',
       dataType:'xml', 
       data: captcha_value
       success: function(data) {
          if($(data).find('message').text() == "true"){
             //now you get the true. do whatever you want. even call a function
            }
          else{
        //and false
          }
       }
});

this is my solution probably works for you also. I always prefer xml for communication. Thats my choice.

$.ajax({
    type: "POST",
    url: '/captcha_check.php',
    data: captcha_value,
    dataType: "text",
    success: function(data) {
        if(data == "true") {
            // correct
        } else {
            // nope
        }
    }
});
dataType: 'json', //Important:Sometimes JQuery fails to automatically detect it for you.
success: function(data) {
    console.log(data ? "Data is true" : "Data is false");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM