1

First off, I'm fairly new to JS and PHP. But I have a PHP array that contains the titles of some events. I'm trying to make a Javascript script that creates elements and fills them with the strings in the php array.

Here's kind of what I'm wondering about. Is there a way to do something like this:

function createCard(x) {
  var event_title = "<?php echo $event_title[x]; ?>";
  }

Or if there's a better way to do this, I'm open to suggestions. Thanks!

EDIT:

I was able to fix my own issue by just converting the php array into a js a array and going from there

    var event_title_arr = [<?php echo '"'.implode('","',  $event_title ).'"' ?>];
  • you can't do this at all (this way) ... php creates a page, sends it to browser ... there is no way for the browser to interact with PHP during this creation process. - options include making all event_title available to javascript, or AJAX (see XMLHttpRequest) to get the data from the server as needed – Jaromanda X Dec 05 '16 at 03:06

1 Answers1

0

you have to convert the PHP array to string or json and use in js.

ex, array to string,

function createCard(x) {
        var event_title = "<?php echo implode(',', $event_title[x]); ?>";
        var event_title_arr = event_title.split(',');
        console.log(event_title _arr);
        // play around using JS variable "event_title_arr "
  }

OR

function createCard(x) {
        var event_title = "<?php echo json_encode($event_title[x]); ?>";
        var event_title_arr = JSON.parse(event_title);
        console.log(event_title _arr);
        // play around using JS variable "event_title_arr "
  }
Naga
  • 2,190
  • 3
  • 16
  • 21