skip to Main Content

I am searching for a better way to send my PHP variable to Javascript. Currently I echo the variable in PHP:

<script>
  var numbers = <?php echo $numbers ?>;
</script>

I then access this variable in Javascript like this: class.method(numbers);

My PHP file is included in the index.php before the javascript file, so I have access to this variable in the javascript file.

Now I am looking for a nicer way to submit the PHP variable than using echo. Does anyone have an idea?

The output of numbers looks like:

enter image description here

5

Answers


  1. If you want to mix your php with JS .the one you have used is better .also you can try something like this
    Add a display none span to your html page with id :document_target
    example

    <span id="document_target" style="display: none;"><?=$numbers;?></span>
    

    in js file get data of span with id

     var myNumber = document.getElementById("document_target").textContent;
    
    Login or Signup to reply.
  2. One better alternative would be to output the PHP value to a data attribute. Given that this variable doesn’t seem to be tied to a specific element, you could put it at root level on the body element. Then you can read it from there when the JS executes once the DOM has loaded, like this:

    <body data-numbers="<?php echo $numbers ?>">
       <!-- your HTML ... -->
    </body>
    
    let numbers = document.body.dataset.numbers; // plain JS
    
    let numbers = $('body').data('numbers'); // jQuery
    

    This is under the assumption that the $numbers variable in your PHP is holding a value which can be coerced to a string

    Update

    Given the edit to your question where you clarify that $numbers in fact contains an object, you can instead encode it to JSON, output it to a <script> tag and then use it from there:

    <script type="text/plain" id="numbers">
       <?= $json_encode($numbers) ?>
    </script>
    
    let numbers = JSON.parse(document.querySelector('#numbers').textContent.trim()); // plain JS
    
    let numbers = JSON.parse($('#numbers').text().trim()); // jQuery
    
    Login or Signup to reply.
  3. You can use an inline script tag to add data to the HTML document like this:

    const dataElement = document.querySelector('#phpData'),
      data = JSON.parse(dataElement.text);
      
    console.log(data.example, data.number);
    <!-- This tag is what really is rendered on the page -->
    <script type="text/plain" id="phpData">
    {
      "example": "Example string",
      "number": 10
    }
    </script>
    
    <!-- This tag is written in the source code of the page -->
    <script type="text/plain" id="phpData">
    {
      "someValue": <?=$some_value?>,
      "otherValue": <?=$other_value?>
    }
    </script>

    As can be seen, when running the example, the script with inappropriate JS type attribute is not executed.

    In that script tag you can echo variables or other values as you need (like in the latter example), or even echo a json_encoded string. This is one of the safest way to include PHP variables to JS, and you can still save your actual JavaScript into an external file. The data script must be included in the HTML document, because you can’t access .js files with PHP, and also, for security reasons, JS can’t read text from an external file.

    What comes to the usage of echo, it’s a PHP language construct specifically meant to add content to the markup, there’s no reason to avoid it. I’ve used a short hand of echo in the latter example, but it still is echo.

    Login or Signup to reply.
  4. Here is a possible way to do this:

    1. Get the values from the form fields if there’s a form, or whatever and send them in a query to php from JS, this work regardless where the php file is, it can be a remote file on a different server, or just another local page,etc.

    2. The php file receives the request and reply back

    3. retrieve the reply of the php file in the JS.

    An example of the above using jquery:

    
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    
            $(document).ready(function(){
                $("#submit_button").change(function(){
                    var my_id = "some value here, or do some getelement by id .val()..."
                    
                    $.ajax({
                        url: 'includes/forms.php', //or replace with a remote url
                        method: 'post',
                        data: {  some_requestPHP_name: my_id } //note this line
                    }).done(function(data){
                        console.log(`js got from php =${data}` )
                        //
                          var numbers = data;
    
                        
                    })
                })
            })
    
    
    
    

    Now in the php file you need to make the file react whenever it recieves something containing the line I indicated above containing some_requestPHP_name, this is a parameter that you decide

    if (isset($_POST["some_requestPHP_name"]))  echo  some_function(); // you can use the "some_requestPHP_name" just as a trigger to call the some_function of you can use the data from it
    
    function some_function(){
    // do things and return the number;
    return 1;
    }
    
    
    
    

    Depending on your usage you may not have a form/button etc so you may want to remove the .change() and execute the function right away, at this point it’s up to you to adapt the example to your needs.

    Login or Signup to reply.
  5. Well, I did it like this:

    <script src="./assets/scripts/tableActions.js"></script> <!-- JS SCRIPT -->
    <table class="w-full" id="table">
                    <thead>
                        <tr><th class='border-b p-2 w-52 border-gray-400'>Full Name</th><th class='border-b border-l p-2 w-52 border-gray-400'>Username</th><th class='p-2 border-l border-b w-36 border-gray-400'>Role</th><th class='p-2 border-l border-b border-gray-400'>E-mail</th></tr>
                    </thead>
                    <tbody>
                    <?php
                        include('./functions/connectSQL.php');
                        $sql = "SELECT * FROM users";
                        $result = mysqli_query($con, $sql);
                        $x = 1;
                        while ($row = mysqli_fetch_assoc($result)) {
                            
                            echo "<tr class='hover:bg-gray-800 cursor-pointer' onClick='returnValues(".$x.");' id='tableRow'><td class='border-t p-2 px-4 border-gray-400' id='fullnameCell'>" .$row["fullname"]  . "</td><td class='border-l border-t p-2 px-4 border-gray-400' id='usernameCell'>".$row["username"]."</td><td class='border-l border-t p-2 px-4 border-gray-400' id='roleCell'>" . $row["role"] . "</td><td class='border-l border-t p-2 px-4 border-gray-400' id='emailCell'>" . $row["email"] . "</td></tr>";
                            $x++;
                        }
                        mysqli_close($con);
                    ?>
                    </tbody>
                </table>
    

    See, that onClick='returnValues(".$x.");' have inside itself variable from PHP. So you will give varibale to javascript using function. Now it is like you probably know:

    function returnValues(x){
        const table = document.querySelector('table');
        const cells = table.querySelectorAll('td');
        const values = Array.from(cells).map(cell => cell.innerText);
        var tableRow = document.getElementById("table").rows;
        var form = document.getElementById("form");
        const usernameField = document.getElementById('usernameForm');
        for (i = 0; i < tableRow.length; i++){
            let tableCells = tableRow[x].cells[i].innerHTML;
            form.elements[i].value = tableCells;
        }
    
        if(values.includes(usernameField.innerText)){
            formButtonAdmin.innerText = "Update";
        }
    }
    

    Now you could be good, when you will have any other questions, feel free to ask 😀
    Have a nice day!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search