Home > other >  How can i convert the PHP string into an integer, but php string is fetched from javascript written
How can i convert the PHP string into an integer, but php string is fetched from javascript written

Time:12-27

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>if else in php</title>
</head>

<body>

    <script>
        var a = 123;
        //to send the prompt value to php, reference taken from stack overflow
    </script>
    <?php
    $a = "<script>document.writeln(a)</script>";
    echo $a;
    ?>
</body>

</html>

in the code above, i fetched the value of javascript variable 'a' in PHP i successfully get it in the variable $a and i tried to print it then also it got printed successfully. As $a would be containing number '123' in string i tried to convert it into an integer using intval() function but, it always shows me value of $a as 0 when i echo it. the below code describes the same

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>if else in php</title>
</head>

<body>

    <script>
        var a = 123;
        //to send the prompt value to php, reference taken from stack overflow
    </script>
    <?php
    $a = "<script>document.writeln(a)</script>";
    $a = intval($a);
    echo $a;
    ?>
</body>

</html>

CodePudding user response:

You have to submit it to the server to process it. Here a working example.

<?php

$canDrive = false;

// use GET to retrieve the value of the "age" query string

if(isset($_GET["age"]) && $_GET["age"] >= 18) $canDrive = true;



?>


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>if else in php</title>
</head>

<body>

    <!-- Here goes your code   -->
    <?php
    if ($canDrive) {
        echo "You can drive";
    } else {
        echo "You can't drive";
    }
    ?>


<form action="" method="get">
        <input type="text" name="age" id="">
        <input type="submit" value="submit">
    </form>

</body>

</html>

Remember, JavaScript and PHP can't communicate directly.

  • Related