PHP changing value inside JS

pass php variable to javascript function
passing javascript variable to php in the different page
how to pass javascript variable value to php variable in same page
pass javascript variable to php
wordpress pass javascript variable to php
php echo in javascript
how to convert javascript variable to php variable
how to use javascript variable in php sql query

I would like to change the text color depending of what page is clicked using PHP.

HTML

<a class="link" href="index.php?col=red">Red</a>
<a class="link" href="index.php?col=gre">Green</a>
<a class="link" href="index.php?col=yel">Yellow</a>
<?php
    if (isset($_GET['col'])) {
        $color = $_GET['col'];
    }else{
        $color = "red";
    }
?>
<div class="toChange">
    Color is changing
</div>

Script

$('.link').click(function () {

    var jcolor = <?php echo $color; ?>;

    if (jcolor == "red") {
        $(".toChange").css({
            "color": "red"
        });
    }
    if (jcolor == "gre") {
        $(".toChange").css({
            "color": "green"
        });
    }
    if (jcolor == "yel") {
        $(".toChange").css({
            "color": "yellow"
        });
    }
});

Why does not work? I also tried to insert a console.log(jcolor) for to see if the jcolor takes the correct value and os ok.

PHP(server-side) runs first when page reload after PHP javascript(client-side) code runs...

So,

This code runs first when page loads

<?php
        if (isset($_GET['col'])) {
            $color = $_GET['col'];
        }else{
            $color = "red";
        }
  ?>

Now, color is red

When you click on the link

this JS will run first

<script>

    $('.link').click(function(){

        var jcolor = <?php echo $color; ?>;


        if (jcolor == "red") {
            $(".toChange").css({"color": "red"});

        }
        if (jcolor == "gre") {
            $(".toChange").css({"color": "green"});

        }
        if (jcolor == "yel") {
            $(".toChange").css({"color": "yellow"});

        }


    });

    </script>

it will change the color, but after that page will reload because you clicked on the link...

Now, let you clicked on Green

<a class="link" href="index.php?col=gre">Green</a>

Your new URL Will be index.php?col=gre

This code will run again

<?php
        if (isset($_GET['col'])) {
            $color = $_GET['col'];
        }else{
            $color = "red";
        }
  ?>

So, the problem is instead of .click event of javascript use. (document).ready and your problem will be solved...

<script>

        $(document).ready(function(){

            var jcolor = <?php echo $color; ?>;


            if (jcolor == "red") {
                $(".toChange").css({"color": "red"});

            }
            if (jcolor == "gre") {
                $(".toChange").css({"color": "green"});

            }
            if (jcolor == "yel") {
                $(".toChange").css({"color": "yellow"});

            }


        });

        </script>

Set or change PHP variable in JavaScript, You cannot pass variable values from the current page javascript to the current page PHP code PHP code runs at the server side and it� Exchanging variables between JavaScript and PHP. How JavaScript variable are retrieved from PHP script? And conversely, how to use the values of PHP variables in JavaScript? Form's data will be in $_POST or $_GET . Using the content of forms in PHP. Name of elements of a form are also PHP variables as soon as the PHP script is the action of the

Change this:

var jcolor = <?php echo $color; ?>;

to this:

var jcolor = '<?php echo $color; ?>';

Note: this is vulnerable to XSS. You are injecting code directly from user input and this is extremely dangerous. Sanitize this input before printing it into the page.

Exchanging variables between JavaScript and PHP, And conversely, how to use the values of PHP variables in JavaScript? want to change dynamically the value to pass to the script, you can assign the value� Set or change PHP variable in JavaScript. Ask Question Asked 5 years, 4 months ago. Active 1 year, you cannot assign Javascript value to PHP variable, yea but you

Try changing your script by below code, No need to trigger click event on .link because you already clicked on link (<a>) and got color from URL, Also whenever you assign values from PHP variable to JS, Put Single or Double quotes around PHP code like this '<?php echo $color; ?>'

<script>

    var jcolor = '<?php echo $color; ?>';


    if (jcolor == "red") {
        $(".toChange").css({"color": "red"});
    }

    if (jcolor == "gre") {
        $(".toChange").css({"color": "green"});
    }

    if (jcolor == "yel") {
        $(".toChange").css({"color": "yellow"});
    }

</script>

Passing PHP Variables to JavaScript, We demonstrate with string, boolean, and numeric values (i.e., scalar values). To pass scalar data held in a PHP variable ( $val ) to a JavaScript variable, place� You can’t directly manipulate a session value from Javascript – they only exist on the server. You could let your Javascript get and set values in the session by using AJAX calls though. See also. Javascript and session variables; jQuery click event to change php session variable

JS expecting string value and that because later on you compare towards if (jcolor == "red") {,

so what you actually doing is assigning variable to another which is i am sure it will print you an error if you look up the console you will find undefined for the mentioned variable

so all what you need is just add the value as a string inside ""

var jcolor = "<?php echo $color; ?>";

How to pass JavaScript variables to PHP ?, The way to pass a JavaScript variable to PHP is through a request. Method 1: A cookie named gfg is created in the code below and the value� How to change the value of a global variable inside of a function using JavaScript ? Pre-requisite: Global and Local variables in JavaScript Local Scope: Variables which are declared inside a function is called local variables and these are accessed only inside the function.

How to change the value of a global variable inside of a function , first_page How to rotate an HTML div element 90 degrees using JavaScript ? Next. last_page How to turn off PHP Notices ? Writing code in� Using jquery val () method: The val () method is used to return or set the value attribute of the selected elements. In default mode this method returns the value of the value attribute of the FIRST matched element & sets the value of the value attribute for ALL matched elements.

Variable variables - Manual, They are most useful when accessing values within a property that contains an Sometimes you might wish to modify value of an existing variable by its name. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.

JavaScript Arrays, [1] is the second element. Changing an Array Element. This statement changes the value of the first element in cars : cars[0]� To pass scalar data held in a PHP variable ($val) to a JavaScript variable, place the following in a JavaScript segment: var val = "<?php echo $val ?>"; Notice the quotes around the PHP tags. This will result in a string value in JavaScript which you may need to convert for use in your scripts.

Comments
  • Edit: thanks for reply originally the code was with a number this i why I forget ' '. The problem now is that when you select a color the text changes colo for few millisecond then it returns black. I think is a problem of refresh or something similar. So when i click a color the text color change for a bit millisecond then the page refresh and text returns black. How can I avoid refresh?
  • Thanks but almost works. Now the text changes for a bit of millisecond and then return black. Maybe there a re a loop problem or something similar