1

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.

2
  • What do you mean pass these values to js without relying on the page url? Why don't you just hardcode these values then? Commented Dec 16, 2015 at 19:30
  • Well, these values are dynamically generated. :P Commented Dec 16, 2015 at 19:33

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

5 Comments

This makes sense. And I can just use the variable data in js. Thanks! I will give it a try! =)
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.
Nope. The whole point was to put it into the Javascript, and everything in Javascript is visible in the client.
If you want to hide the data, you have to keep it on the server, and send a request to the server.
Your question said you didn't want to send an AJAX request to the server.
1

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());

1 Comment

You should use single quotes around the value, because JSON uses double quotes around strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.