Mohammad Shojaa Mohammad Shojaa - 3 months ago 18
Ajax Question

compare session variable with post variable via ajax request

I want when captcha code complete from user a request sent to a page and compare input string by user with value of captcha image (this value strore in session value)

this is page contain ajax request(here isn't img tag but it isn't important!):

<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input id="captcha" maxlength="5" onkeyup="myFunction()" value="">
<script>
function myFunction() {
var x = document.getElementById("captcha");
if(x.value.length==5){
$(document).ready(function(){
$.get("test.php",
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
}
}
</script>
</body>
</html>


and this page is that get post request:

<?php
session_start();
$c=$_POST['captcha']; echo $c;echo gettype($c);
$s=$_SESSION['captcha']; echo $s;echo gettype($s);
if($c==$s) {
echo 'correct';
} else {
echo 'incorrect';
}
?>


but in response: type of session variable is
NULL
! why?!

but type of post variabel is string

but i sure session and post are equal.

And now how compare with together!

Answer

This problem sloved! but i don't how exactly!

I work on serach ajax and of course again start sessions.

but it doesn't have problem before and after work on it.

but i thought better is on page that send request, session started.

and it worked!

then i deleted session_start() statement but it still worked :D

i think the code not in the mood :))

code of page send request:

<html dir="rtl">
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<img id="captcha" src="captcha.php" width="160" height="45" border="1" alt="CAPTCHA">
<small><a href="#" onclick="
document.getElementById('captcha').src = 'captcha.php?' + Math.random();
document.getElementById('captcha_code').value = '';
return false;
">refresh</a></small>
<input id="fname" type="text" name="captcha" size="6" maxlength="5" onkeyup="myFunction()" value="">
<small id="massage-captcha">input number show on the image.</small>
<script>
function myFunction() {
var x = document.getElementById("fname"); 
if(x.value.length==5){
    document.getElementById("massage-captcha").innerHTML = "please wait!";
    $(document).ready(function(){
        $.post("test.php",
        { 
        captcha: x.value
        },
        function(data,status){
            if(data=="correct"){
                document.getElementById("massage-captcha").innerHTML = "correct";}else{
                document.getElementById("massage-captcha").innerHTML = "incorrect";
            }
        });
    });
}
else{
    b.value="";
}

}
</script>

and file recive request:

<?php
session_start();
if($_POST['captcha']==$_SESSION['captcha']){echo 'correct';}
else{echo 'incorrect';}
?>

my last idea: session on the server removed after past pne day and now work fine!

Comments