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; ?>" ; });
If at all you want to send php value to php page using jquery and ajax, then first of all, create input text with type hidden. put your php value in it. and when you click then get that value from that input type hidden in jquery and then pass it to whichever page you want.
PHP works on the server side, in other words, at the web server. Therefore, for JavaScript to assign values to PHP variables, the values must be submitted to the web server. The following HTML file, called index. html, includes the JavaScript source code.
Create an hidden input tag in HTML , then set it's value as a JSON string with jquery. Next whenever you need that data , simply call the PHP function which returns value of input tag . Now you can convert the JSON data and store it in PHP variable.
It really depends if you are using some sort of a template engine.
If you're using plain PHP, the only option for you is to echo
the variable:
var current page = "<?php echo $your_var; ?>";
Twig engine:
var current page = "{{ your_var }}";
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With