I need to send some data to a web page, ideally in json format and I wonder what method is considered best, and why. Overall what good or bad experiences and surprises you had with them.
-
<script>var myJson = <? echo json_encode($myVar);
?>;</script>advantage: the json is directly in javascript, were it will be used.
inconvenient:<script>in the middle of html/dom is bad (js belong
to .js files). -
<div data-myJson='<? echo json_encode($myVar); ?>'>advantage: html5 data thing is easy to work with.
inconvenient:
bunch of data in the dom, it doesn’t look elegant note: in my
case, I can afford to ignore “old” browsers. -
ajax everything.
advantage: the json doesn’t even need to be sent in this case, as it
will be already available (no page change).
inconvenient: not
really an option as I would need to rewrite the full website. -
instead of sending the full json, store it in the session and send a
key.advantage: less data moving around
inconvenient: the
data/session couple needs to be kept track of, and I like my session to be kept clean and tidy. (even if user just close the page before the flow is
finished) (which won’t close the session). -
Cookies.
advantage: herr.. is reverse evil a good thing?
inconvenient: like session variables, but out of the cage. -
Store the json in the session, and ajax it when the page is loaded.
advantage: somewhat elegant conceptually.
inconvenient: heavy, as the ajax instruction has
to be added to a js file, and the session has to be managed. (and
cleansed. if the page load doesn’t finish, the json will stay until
I cleanse it or the session finishes). Plus the html header means more bandwidth, and the we have to wait for the success to use the object. - other?
edit: as there seems to be a bit of confusion, with option 3 “ajax everything” I was meaning one page load, and all content loaded by ajax, even if you go through menus, links to other pages, forms submit, and such. I consider a more traditional navigation, (pages sent by the server as new a pages), with a page doing an ajax request to retrieve some value (here, my json object) on the server, as point 4 “session”, as the main data has to remain on the server after the page has been sent to be later fetched by the ajax request. I did add option 6 for this.
I unhesitatingly recommend #1. You want to use your data in javascript, right? #1 is the simplest way and most direct way to ensure that your data exists, as a plain-old javascript object, when the page loads. I transfer data from the server side to the browser side all the time this way and it works beautifully.
You could arguably create better separation between your data and your UI by loading your data in an ajax call, but this is an additional http request, which will slow your page load.