Steve Kim
Steve Kim

Reputation: 5591

Passing array values to js

So current setup is as following:

PHP:data.php

<?php
$method = $_SERVER['REQUEST_METHOD'];
$data = array(
    "16508",
    "16498",
    "16506" 
);
if ($method === "GET") {    
    echo json_encode($data);
}
?>

JS:

$.get("./page_asset/data.php").then(function(returned) {
        data = JSON.parse(returned);    
};  

Now, how do I parse the data without getting the specific php page (as I don't want to rely on the specific php address such as "/page-asset/data.php").

For example:

PHP:

<?php
  $data = array(
    "16508",
    "16498",
    "16506" 
   );   
?>

I simply want to pass these values to js without relying on the page url.

Upvotes: 1

Views: 80

Answers (2)

Pablo Digiani
Pablo Digiani

Reputation: 602

You can use a hidden field:

<input id="my-data" type="hidden" value='<?php echo json_encode($data)?>' />

And then you can parse the input value from javascript:

var data = $.parseJSON($('#my-data').val());

Upvotes: 1

Barmar
Barmar

Reputation: 780714

You can use PHP to create the Javascript in the original page. json_encode() can be used to convert a PHP value to the analogous JS literal.

<?php
  $data = array(
    "16508",
    "16498",
    "16506" 
   );   
?>
<script>
var data = <?php echo json_encode($data); ?>;
</script>

Upvotes: 2

Related Questions