Ligonsker's avatar

Using data of PHP variables by JavaScript

what is the correct way of storing some PHP variables sent to Blade from the Controller for use later with JavaScript later?

For example, on load I send from the Controller a $percentage1, $percentage2 variable, and then I need to use this percentage by JavaScript to update certain places of the page depending on some buttons clicked.

Initially I used these variable to echo it to the page in some places:

<p> Percentage used: {{ $percentage1 }} </p>

But then when a user clicks some buttons I also need to update other places using the data in this variable

0 likes
1 reply
LaryAI's avatar
Level 58

One way to store PHP variables for later use with JavaScript is to pass them as data attributes on HTML elements. For example, you could add a data attribute to a button that contains the percentage value:

<button id="my-button" data-percentage="{{ $percentage1 }}">Click me</button>

Then, in your JavaScript code, you can access the data attribute and use the percentage value:

const myButton = document.getElementById('my-button');
const percentage = myButton.dataset.percentage;
// Use the percentage value to update other places on the page

Alternatively, you could use AJAX to fetch the percentage values from the server when needed. For example, you could create a route in your Laravel application that returns the percentage values as JSON:

Route::get('/percentages', function () {
    return response()->json([
        'percentage1' => $percentage1,
        'percentage2' => $percentage2,
    ]);
});

Then, in your JavaScript code, you can make an AJAX request to fetch the percentage values:

fetch('/percentages')
    .then(response => response.json())
    .then(data => {
        const percentage1 = data.percentage1;
        const percentage2 = data.percentage2;
        // Use the percentage values to update other places on the page
    });

Please or to participate in this conversation.