roberts roberts - 2 months ago 10
PHP Question

I need to calculate random value without refreshing page in php

in submitting the data from form random value will changed.

$x=rand('1000','9999');
echo $x;

<form method="post">
<input type="number" name="rnd">
<input type="submit" value="Submit">
</form>

$a = $_POST['rnd'];
if($a === $x){
echo "Match";
}

Answer

I think you are looking for something like below.

<?php
    $x=rand('1000','9999');
    echo $x;
?>
<script type="text/javascript">
    var rand_value = "<?php echo $x?>";
</script>
<form method="post" onsubmit="return validateForm()" >
<input type="number" name="rnd" id="rnd">
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
    function validateForm(){
        x = document.getElementById("rnd").value;
        if(rand_value == x){
            alert("Match");
            return true;
        }else{
            alert("Not-Match");
            return false;
        }
    }
</script>

If you want to do validation on client side you should use JavaScript.

else try this

<?php 
    $x=rand('1000','9999');
    echo $x; 
?>

<form method="post">
<input type="hidden" name="myRnd" value="<?php echo $x; ?>">
<input type="number" name="rnd">
<input type="submit" value="Submit">
</form>
<?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $x = $_POST['myRnd'];
        $a = $_POST['rnd'];
        if($a === $x){
            echo "Match";
        }
    }
?>
Comments