Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass php variable's value to jquery

Tags:

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; ?>" ;  }); 
like image 320
user1592380 Avatar asked Jun 05 '13 18:06

user1592380


People also ask

How set PHP variable value in jquery?

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.

Can we access PHP variable in JavaScript?

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.

How can get jquery variable value in PHP without Ajax?

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.


2 Answers

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.

like image 144
tftd Avatar answered Nov 01 '22 14:11

tftd


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.

like image 22
Dhamesh Makwana Avatar answered Nov 01 '22 12:11

Dhamesh Makwana