myro
myro

Reputation: 1206

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';
?>

Upvotes: 1

Views: 3543

Answers (3)

mmhan
mmhan

Reputation: 731

dataType: 'json', //Important:Sometimes JQuery fails to automatically detect it for you.
success: function(data) {
    console.log(data ? "Data is true" : "Data is false");
}

Upvotes: 1

savruk
savruk

Reputation: 545

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.

Upvotes: 2

iRaivis
iRaivis

Reputation: 169

$.ajax({
    type: "POST",
    url: '/captcha_check.php',
    data: captcha_value,
    dataType: "text",
    success: function(data) {
        if(data == "true") {
            // correct
        } else {
            // nope
        }
    }
});

Upvotes: 1

Related Questions