Haroldo
Haroldo

Reputation: 37377

best way to store php data on a page for use with javascript/jquery?

Ok, so im trying to work out the fastest way of storing data on my page without slowing the page load:

The events anchors are created with a php loop, so i could create the data elements within this loop using either

  1. use un-semantic tags ie rel="some_data"
  2. create a jquery.data() for each iteration of the loop

or i could run the loop again, separately, this time inside script tags with jquery.data();

would really appreciate any thoughts on this!

Upvotes: 2

Views: 746

Answers (1)

Pascal MARTIN
Pascal MARTIN

Reputation: 400932

A possibility would be to generate, on the server-side, a Javascript array or object that contains all the events, and inject it into the page as a Javascript variable.

Basically :

  • On the PHP side :
    • Build the array of events
    • Transform it to Javascript, using json_encode
    • Inject it into the HTML page.
  • And, later, on the JS side :
    • Just use that Javascript variable.

Great thing with that solution it that is work for almost any possible kind of data, is quite fast, and quite easy to develop.


The generated HTML+JS code would look like this :

<script type="text/javascript">
    var myArrayOfEvents = [ ... ];
</script>

And it could be generated with some PHP code like this :

<script type="text/javascript">
    var myArrayOfEvents = <?php echo json_encode($myEvents); ?>;
</script>


Of course, up to you to :

  • Define the structure you want for your events
  • Build it in PHP
  • Use it in Javascript

Upvotes: 3

Related Questions