Welcome Guest, Not a member yet? Register   Sign In
Using "PHP" inside front end scripts
#5

(07-02-2015, 08:47 AM)kamenjan Wrote: Are you aware of any online resources describing this methodology? I tried searching for something like "using php cached variables in script", but was unsuccessful.

This is how I managed to parse cached array ($survey->answers) to js array (var answers) in my view:


PHP Code:
<?php
$js_answers 
json_encode($survey->answers);
?>


Code:
<script>
   var JSON_array = <?= $js_answers ?>;
   var answers = [];

   for (var answer in JSON_array) {
       if (JSON_array.hasOwnProperty(answer)) {
           answers.push(JSON_array[answer].answer);
       }
   }
</script>
 
But based on what you wrote, I would image this is not the most effective/scalable approach.

The basic idea is to echo the $js_answers variable into the HTML in your view instead of your script, then use JavaScript to retrieve the value from the DOM and pass it into your script. In most cases, you can encapsulate most of your code into reusable .js files with objects/functions/methods, which you can read about almost anywhere (I prefer https://developer.mozilla.org, but in some areas they don't do much more than give you the specs).

Then you can either:
- determine a convention to follow within your Views' HTML to pass data to your script and create a common script you use to check for the presence of the data and call the appropriate methods in your JS; or
- add a small script to individual Views as needed to retrieve the data and call the appropriate methods.

For example, if you're using jQuery, you might do something like this:
Code:
<div id="surveyResultsDiv" data-answers="<?php echo $js_answers; ?>">
</div>
<script>
// Assuming the script which handles this data is available via myScript.graph()
myScript.graph($('#surveyResultsDiv').attr('data-answers'));

</script>
Reply


Messages In This Thread
RE: Using "PHP" inside front end scripts - by mwhitney - 07-02-2015, 11:18 AM



Theme © iAndrew 2016 - Forum software by © MyBB