The code looks like this:
PHP file
<?php
...
$arrayName = ['ArrayValue_0', ..., 'ArrayValue_n'];
...
php?>
JavaScript
$('.elementClass').each(function(index, id) {
$(id).html('<?php echo $arrayName[index - 1]?>');
});
But you can't just insert a JavaScript variable like that into php tags so index is never received. I know this can be done via AJAX but is there any other way? Thanks in advance.
Additional info: I've been told to do this in PHP so there's no posibility of switching the array to a JS file.
The code looks like this:
PHP file
<?php
...
$arrayName = ['ArrayValue_0', ..., 'ArrayValue_n'];
...
php?>
JavaScript
$('.elementClass').each(function(index, id) {
$(id).html('<?php echo $arrayName[index - 1]?>');
});
But you can't just insert a JavaScript variable like that into php tags so index is never received. I know this can be done via AJAX but is there any other way? Thanks in advance.
Additional info: I've been told to do this in PHP so there's no posibility of switching the array to a JS file.
Share Improve this question asked May 15, 2013 at 9:49 Jesús CruzJesús Cruz 1922 silver badges19 bronze badges 1- 1 PHP is a server-side language. When the client receives the page, the PHP code is already executed. So no, there's no way you can do it with this trick. – MaxArt Commented May 15, 2013 at 9:52
3 Answers
Reset to default 8You can define arrayName
variable in JS and initialize it with the value from the server:
var arrayName = <?php echo json_encode($arrayName); ?>;
$(".elementClass").each(function(index, id) {
$(id).html(arrayName[index-1]);
});
What you're trying to do will not work. For example this:
$(id).html('<?php echo $arrayName[index - 1]?>');
The above will never, ever work, because PHP is run on a server, not on your user's browser.
What you need to do is send the variable somehow to the server. You have a plethora of options:
- Use a form and read a
$_POST
variable - Append it to a URL and read a
$_GET
variable - Use AJAX and asynchronously send that variable to the server
- Return the whole array from PHP to your Javascript code
- etc. etc.
Remember, PHP runs on the server, which renders the page, which then in turn is read by your browser where you run Javascript. You can't paste PHP code into the page and expect it to be parsed by PHP!
You need to get back to the server if you wish to get info from it (PhP runs on the server), so either you create a javascript variable on-the-fly when loading the page with the plete content of your PhP array , either you use ajax to get back to the server without refreshing the whole page.