0

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

sbgib
  • 5,580
  • 3
  • 19
  • 26
  • Actually, you should not mix JS and PHP at all. If you need data on a page, fetch it with AJAX, or include it in a script tag with an appropriate type attribute. – Teemu Jan 15 '21 at 09:41
  • Maybe a hidden field where the value is the php variable and then you may retrieve the field value with javascript – cwhisperer Jan 15 '21 at 09:48
  • @Rory McCrossan How can I attach data to HTML in the smartest way, because in my opinion I have to do it also with echo, because HTML does not know the PHP variables. – Christian Teubner Jan 15 '21 at 09:49
  • @ChristianTeubner I added an answer for you below – Rory McCrossan Jan 15 '21 at 09:55
  • 1
    @Teemu I agree with you completely. I removed my comments as they could be misconstrued. – Rory McCrossan Jan 15 '21 at 09:56
  • 1
    @RoryMcCrossan Though manipulating JS with PHP is a very commonly used practice ( is delicious, millions of flies can't be wrong, can they?), I've started to advice against it. You can imagine a fresh developer failing their first security audit, and then them explaining "But I got the code from SO ..." The dev won't feel very comfortable, and it's also bad promotion to SO too. I know I've already lost the war, but still continuing the battle, maybe we needed a canonical answer to this question, and use it like [this dup target](https://stackoverflow.com/q/13840429) ..? – Teemu Jan 15 '21 at 13:18

5 Answers5

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;
Merin Ovelil
  • 367
  • 2
  • 9
  • This is correct way to "inject" PHP into JS. Appending PHP variable to HTML make it work as a template which is just a dynamic generated HTML code and such code shall be used by JS. – Rafał Świerczek Jan 15 '21 at 10:01
1

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.

Teemu
  • 22,918
  • 7
  • 53
  • 106
1

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.

user206904
  • 504
  • 4
  • 16
0

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
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

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 :D Have a nice day!

  • This is just one more "_fly_", inline event listeners are equally bad practice like PHP and JS mixing. – Teemu Jan 11 '23 at 07:48