user1592380
user1592380

Reputation: 36367

How to pass php variable's value to jquery

I have a php variable:

$name_of_current_page

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; ?>" ;

});

Upvotes: 23

Views: 93989

Answers (4)

tftd
tftd

Reputation: 17062

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.

Upvotes: 33

Carlos
Carlos

Reputation: 4637

First at all, that you ask, is a normal way on fill client side code, but this one will be load at the page load, if you want to run it on live once the page is loaded, you must use ajax, cause is the way on how you will comunicate with the server side scripts, is no possible jquery or javascript load the php vars on live once the page have been loaded

Upvotes: 0

Dhamesh Makwana
Dhamesh Makwana

Reputation: 109

var current page = "" ;

I don't think you can have spaces in a variable. (i could be wrong).

Anyway to simplify your code, I've just done re-done it slightly.

$name_of_current_page = "HomePage";

And for the Javascript;

var currentPage = "<?= $name_of_current_page; ?>";

That should be it.

Upvotes: 6

Zach Leighton
Zach Leighton

Reputation: 1941

document.title should give you what you need.. things like this either query the DOM or Ajax imho.

I find it best to separate layers, and not mix presentation and controller with peppered html/php code.

Upvotes: 0

Related Questions