How to validate jQuery/AJAX input value in external php file and return back the result?
I have a variable called captcha from input in my form.
In my javascript file I have this:
var captcha = $("input#captcha").val();
$.ajax({
type: "GET",
url: "includes/process.php",
data: captcha,
success: function() {
alert('Captcha is OK');
}
});
In my process.php file I have this:
<?php
// Begin the session
session_start();
// To avoid case conflicts, make the input uppercase and check against the sessi开发者_StackOverflow中文版on value
// If it's correct, echo '1' as a string
if(strtoupper($_GET['captcha']) == $_SESSION['captcha_id'])
echo 'true';
// Else echo '0' as a string
else
echo 'false';
?>
And my problem is that it always pass as OK, no matter what I type into input. How can I e.g. sand back to my javascript containing file the value of captcha_id so I can check it e.g. using alert in javascript?
I think that my php file is wrong, because no matter what I type into my captcha (I have checked it using alert(captcha); after var captcha = $("input#captcha").val(); and it alert the correct value.
So, I assume that the success: ... part is wrong
or
the php comparison part in process.php . What does it have to return for success part of ajx to be executed?
Thanks for any advice.
SOLVED ! at least for me ;)
This is working for me :
$.ajax({
type: "GET",
url: "includes/process.php",
data: "captcha=" + captcha,
success:function(data){
if(data=='true')
alert("OK");
else
alert("not ok");
}
});
process.php remains untouched.
Thanks you all, you have helped me a lot.
I believe your ajax call is wrong :
data:{captcha:yourValueFromYourInput}
Then serverside you have $_GET['captcha']=yourValumeFromYourInput
The success function will be called as soon as an ajax response is available. In your case, it is either true or false. So, you should check that:
success: function(response) {
if (response == 'true' )
// captcha valid
else
alert ('wrong');
}
you are not capturing the response from the server in your success call back
success:function(data){
if(data=='true')
alert("OK");
else
alert("not ok");
}
also you may need to send the data
in your ajax call as
data:{captcha:captcha},
精彩评论