user61629 user61629 - 1 year ago 90
Javascript Question

How to pass php variable's value to jquery

I have a php variable:


which I have available in my view, and I want to make the value available to jquery. Is the best way to do it like the following?

$(document).ready(function () {
var current page = "<?php echo $name_of_current_page; ?>" ;


Answer Source

It really depends if you are using some sort of a template engine.

  1. If you're using plain PHP, the only option for you is to echo the variable:

    var current page = "<?php echo $your_var; ?>";
  2. Twig engine:

    var current page = "{{ your_var }}";
  3. Smarty and RainTPL engines:

    var current page = "{$your_var}";

As you can see, there are other ways. All of them work fine. It really depends on how you'd like to write and organize your code. I personally use Twig and find it really easy,fast and straightforward.

Also, as others have pointed out, you can do AJAX calls to the server and fetch the variables like that. I find that method time-consuming, inefficient and insecure. If you choose this method, you will be posting requests to a script. Everybody will be able to do post/get requests to that script which opens your doors to some bots and DoS/DDoS attacks.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download