How to declare php variable in javascript

I want to declare a PHP variable (most preferably a session variable) inside a javascript function.

Here is my html

Service:

and here if my javascript function but this is not working.


Basically on option change, I want a session variable to hold the value of option whichever is selected. Is there any way to do it?

asked Oct 28, 2015 at 5:21

How to declare php variable in javascript

6

You can not set php variable using javascript, use Ajax instead.

Actually php is a server side language and is executed until your webpage if fetching data from server as soon as your page gets completely loaded you loose the access to php variables.

You can achieve this only by AJAX

And to do it with ajax on your current page you can write a function like

$("#selected").on("change", function () {
    $.ajax({
    method: "POST",
    url: "http://url.of/somepage/",
    data: { sessionvalue: this.value }
    })
});

and then on http://url.of/somepage/ you can do

$this->session->data['desired_service'] = $_POST["somepage.php];

answered Oct 28, 2015 at 5:28

ArpitaArpita

1,3541 gold badge15 silver badges35 bronze badges

1

try this code:-


answered Oct 28, 2015 at 5:22

How to declare php variable in javascript

4


answered Oct 28, 2015 at 5:27

Raja CRaja C

1391 silver badge12 bronze badges

1

How to declare php variable in javascript

Sometimes, you may need to declare dynamic JS variables using PHP.

One thing you can do is to manually write the JS code as following.

var x = " echo $name ?>";

Enter fullscreen mode Exit fullscreen mode

But, we can create a function to do this easily with a better data types support.

function phpVarsToJs($vars) {
    echo '';
}

Enter fullscreen mode Exit fullscreen mode

This function requires an PHP array, which contains key/value pairs which are the Javascript variable name and the value. Also, this function automaically creates Javascript variables according to the data type of the PHP variable.

PHP Arrays will be converted into JSON format. If you don't need the '