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.
asked Dec 16, 2015 at 19:28
Steve Kim
5,66117 gold badges61 silver badges100 bronze badges
-
What do you mean pass these values to js without relying on the page url? Why don't you just hardcode these values then?void– void2015年12月16日 19:30:21 +00:00Commented Dec 16, 2015 at 19:30
-
Well, these values are dynamically generated. :PSteve Kim– Steve Kim2015年12月16日 19:33:32 +00:00Commented Dec 16, 2015 at 19:33
2 Answers 2
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>
answered Dec 16, 2015 at 19:31
Barmar
789k57 gold badges555 silver badges669 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Steve Kim
This makes sense. And I can just use the variable
data in js. Thanks! I will give it a try! =)Steve Kim
Just a quick question. Is there a way to make the values not visible in the element inspect? the
echo is showing all the values from the frontend and was wondering if there is a way to hide the values.Barmar
Nope. The whole point was to put it into the Javascript, and everything in Javascript is visible in the client.
Barmar
If you want to hide the data, you have to keep it on the server, and send a request to the server.
Barmar
Your question said you didn't want to send an AJAX request to the server.
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());
answered Dec 16, 2015 at 19:35
Pablo Digiani
6025 silver badges9 bronze badges
1 Comment
Barmar
You should use single quotes around the value, because JSON uses double quotes around strings.
default