Get values from PHP to Javascript

passing php to javascript

Check this out…

$valueIsHere = "A Variable defined via php"; //php variable
<!DOCTYPE html>
<html lang="en">
    <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>testing data passing</title>
     <div class="container" data-php="<?php echo $valueIsHere; ?>"> <!--saving variable to the data attr -->
        <h1>Passing value from php to js</h1>
        <p id="result">here</p>
        <button onclick=getData();>Get Value</button>

            function getData() {
                let data = document.querySelector('.container').getAttribute('data-php'); //getting the data from data attr
                document.querySelector('#result').innerHTML = data; //setting the data to the result
                document.querySelector('button').innerHTML = 'Value fetched!';

Leave a comment

Your email address will not be published. Required fields are marked *