One of my readers recently asked how to pass an array or another variable from PHP to JavaScript.
This is a question I've seen all over the internet, and the quick and
dirty answer is that you can't... at least not directly. This is because
PHP is run on the server-side, and JavaScript is run on the client side
(except in rare, experimental cases). You cannot call a JavaScript
function, or access a JavaScript variable directly from PHP because
they run in completely different locations (among other reasons).
That said, here's what you can do to share data between PHP and JavaScript:
- Generate the JavaScript using PHP, just like you do HTML
- Use AJAX to send data from JavaScript to PHP and vice versa
Neither of these methods fully qualifies as "passing variables" like
you would when calling a function with parameters, but they do involve
sending and retrieving data, which can be created from and/or parsed
into variables for any given language.
Generate the JavaScript with PHP
<script>
var my_number = <?php echo 123; ?>;
var my_string = "<?php echo "foo"; ?>";
var my_array = <?php echo json_encode( array( "foo", "bar", "baz" ) ); ?>;
var my_object = <?php echo json_encode( array( "foo" => "bar" ) ); ?>;
</script>
The code above generates JavaScript variables using PHP. This is the
easiest way to control JavaScript using PHP. Numbers and strings are
pretty simple. For more complex variables, like arrays, the json_encode
function can help. It basically converts a PHP data structure into
JavaScript code. This use case isn't exactly what it was intended for
(more on that later), but it's quite handy in this circumstance.
The php code above will generate the following JavaScript code when executed:
<script>
var my_number = 123;
var my_string = "foo";
var my_array = [ "foo", "bar", "baz" ];
var my_object = { "foo": "bar" };
</script>
As you can see, you now have four JavaScript variables created from
data contained in your php script. All you have to do is make sure that
you convert your data into valid JavaScript code!
AJAX / Forms / Links
The other (usually better) way to share data between PHP and
JavaScript is by using HTTP Requests to send and retrieve information
from the web server. Whenever you click a link or submit a form on a
web site, a request is sent from the client to the server, and the
server sends a response back to the client. Thus, you can send data on
a request and receive data from the response. Back in the day, this was
done with links and forms only, but now we have AJAX. AJAX is not so
much a feature of JavaScript as it is a technique of using the
XMLHttpRequest object to send and retrieve data from the server.
Basically the idea is that you can send a request using JavaScript, the
server sends a response, and the response text is then handed back to
the JavaScript code. For more information on AJAX, I highly recommend
reviewing the AJAX Tutorial at w3schools.com.
Here's a sample PHP script that returns a random number between 0 and 100:
<?php echo rand(0,100); ?>
And here's some JavaScript code that makes a request to the PHP script on the web server (using the jQuery library's "get" function):
<script>
// Note: this script sample uses the jQuery library for simplification
jQuery.get( 'random.php', function ( data ) {
alert( "here's a random number: " + data );
});
</script>
The code above makes a GET request to the web server for the
random.php script, which is then executed by the server and the
response is sent from server to client. When the response is received,
the anonymous function is called and passed the response text, which in
this case is simply a random number from 0 to 100.
Note: PHP is not the only language these techniques apply to. Any
language that can be executed on the server-side applies, my personal
favorite being Perl. In addition, there are many formats for data transfer, the most notable being plain text, XML, and JSON.
|