Possible Duplicate:
What's the best way to pass a PHP variable to Javascript?
I am using the following code:
var spge = ;
alert[spge];
The value doesn't alert. What is the mistake?
asked May 5, 2011 at 10:01
1
Essentially:
// then echo it into the js/html stream
// and assign to a js variable
spge = '';
// then
alert[spge];
answered May 5, 2011 at 10:07
4
The most secure way [in terms of special character and data type handling] is using json_encode[]
:
var spge = ;
answered May 5, 2011 at 10:06
Stefan GehrigStefan Gehrig
81.5k24 gold badges155 silver badges185 bronze badges
Put quotes
around the to make sure Javascript accepts it as a string, also consider escaping.
answered May 5, 2011 at 10:06
DunhamzzzDunhamzzz
14.4k3 gold badges48 silver badges74 bronze badges
**var spge = '';**
alert[spge];
answered May 5, 2011 at 10:03
Sai SherlekarSai Sherlekar
1,7821 gold badge16 silver badges17 bronze badges
0
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
In this article, let’s see how to pass data and variables from PHP to JavaScript.
We can pass data from PHP to JavaScript in two ways depending on the situation. First, we can pass the data using the simple assignment operator if we want to perform the operation on the same page. Else we can pass data from PHP to JavaScript using Cookies. Cookie work in client-side.
Program 1: This program passes the variables and data from PHP to JavaScript using assignment operator.
How to pass variables
and
data
from PHP to JavaScript?
GeeksforGeeks
How to pass variables
and
data
from PHP to JavaScript?
var
x =
""
;
document.write[x];
Output:
Here, we just take input by statically or dynamically and pass it to JavaScript variable using the assignment operator. The PHP code in the JavaScript block will convert it into the resulting output and then pass it to the variable x and then the value of x is printed.
Program 2: This program passes the variables and data from PHP to JavaScript using Cookies.
How to pass variables
and
data
from PHP to JavaScript?
GeeksforGeeks
How to pass variables
and
data
from PHP to JavaScript?
var
x = document.cookie;
document.write[x];
Output:
PHP provides a method to set the cookie using the setCookie[] method. Here, we can set the data or variable in PHP cookie and retrieve it from JavaScript using document.cookie.
Steps to Run the program:
- Install local server like XAMPP server into your system.
- Save the file in
htdocs
folder using the namegeeks.php
- Start Apache server.
- Open Browser and type
localhost/geeks.php
in address bar and hit Enter button. - It will display the result.
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.