0

I have a fairly large Application and I'm currently trying to find a way around having to pass Data from PHP (User Tokens for 3rd Party API's and such) through the DOM. Currently I use data-* attributes on a single element and parse the Data from that, but it's pretty messy.

I've considered just making the contents of the element encoded JSON with all the config in, which would greatly improve the structure and effectiveness, but at the same time storing sensitive information in the DOM isn't ideal or secure whatsoever.

Getting the data via AJAX is also not so feasible, as the Application requires this information all the time, on any page - so running an AJAX request on every page load before allowing user input or control will be a pain for users and add load to my server.

Something I've considered is having an initial request for information, storing it in the Cache/localStorage along with a checksum of the data, and include the checksum for the up-to-date data in the DOM. So on every page load it'll compare the checksums and if they are different (JavaScript has out-of-date data stored in Cache/localStorage), it'll send another request.

I'd rather not have to go down this route, and I'd like to know if there are any better methods that you can think of. I can't find any alternative methods in other questions/Google, so any help is appreciated.

2 Answers 2

1

You could also create a php file and put the header as type javascript. Request this file as a normal javascript file. <script src="config.js.php"></script> (considering the filename is config.js.php) You can structure your javascript code and simply assign values dynamically.

For security, especially if login is required, this file can only be returned once the user is logged in or something. Otherwise you simply return a blank file.

Sign up to request clarification or add additional context in comments.

Comments

1

You could also just emit the json you need in your template and assign it to a javascript global.

This would be especially easy if you were using a templating system that supports inheritance like twig. You could then do something like this in the base template for your application:

<script>
MyApp = {};
MyApp.cfg = {{cfg | tojson | safe}};
</script>

where cfg is a php dictionary in the templating context. Those filters aren't twig specific, but there to give you an idea.

It wouldn't be safe if you were storing sensitive information, but it would be easier than storing the info in local storage,

Comments

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.