Supply JSON to a frontend - javascript

I was wondering of the best way to supply JSON data to my frontend. What I'd like to ask is maybe there are some better solutions of doing this which I'm missing out. Here are a couple of obvious thoughts of the top of my head:
1) Simply output JSON data in a template as a global JS variable and
pick it up later on when needed in some JS.
//a template
var json = echo json_encode($data);
//a JS
alert(json.message)
I don't really like this idea. For example, if the frontend is
written completely on JS, I would have to output all the data, even
if it's not really used by the user (I don't know which pages he
would like to visit so I load up data for all the pages). It could
hit performance and just many redundant JSON.
2) Create some JS data provider which requests necessary pices of
data from the server when the user really needs it. The provider also
caches the data it requests so it can instanly return the data
without requesting aything when the user goes back to some page after
visiting it.
What do you guys think? Could you recommend some better solution for
the problem or point out some improvements of the ideas? Thanks.

Related

How to get the values of session using js

I want to know if the user has logged in or not and then display different elements of the navigation based on the username (login by email and password Not username). However, I have no idea how to deal with session. If php and html is separated in two documents, how can I store the required values using session in php document and then get them using javascript in html document? Or should I use cookies instead?
There are a several approaches to do this.
1) You can make a PHP file which will format your $_SESSION data, and all the other data you want as a JSON string (json_encode function in PHP lang). Then use echo to return it. Then use an AJAX request to get this file from javascript or JQuery, and you will receive the data you want. That's a bad approach for this purpose, from my point of view, because after loading the page you send another request to receive a static data, which will not change on the page like email or username.
2) Better approach: PHP is preprocessor hypertext. You can make an php file and write html tags in it, with php output(example: <div><?=$_SESSION['email']?></div>). Search for more info in google ("php inside html").
3) Much better. In modern web programming world its a mistake to use php inside html because you should think not only about how to make something work, you should think how you will maintain it after 3, 6, 12 months later, too. If you use just php inside html in a big project, then, with time, you realize that your code is hard to read and looks ugly. There are plugins that can make your view more readable and maintainable (Twig, Blade, Volt and others). I recommend you use one of them.
The session is a server side thing, you cannot access it using javascript. You can write an Http handler (that will share the sessionid if any) and return the value from there using AJAX

Alternative to passing Data to JavaScript from PHP?

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.
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.
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,

How to dynamically create a JSON file for each Object that gets added to another JSON file

I would like to dynamically create a corresponding JSON file every time a new merchant signs up to my site.
For example:
Burger King signs up to be a merchant on my site. I add Burger king to my merchants.json file. How would I dynamically create a file that gets inserted into that JSON object that can later be used to pull up data specific to that merchant, on that merchants page. For example, a JSON file full of products or deals.
Is this even the right way to go about it?
Can someone point me in the right direction please?
This seems like a very common usage scenario but I don't see any examples online that explain this application structure thoroughly.
NOTE: I am using AngularJS
EDIT: Thanks for the tips guys, after asking around in the #AngularJS channel on IRC, I've been told to go the extra mile and create an API. I'll probably use sails.js to help with that. This obviously isn't how I was planning to do things, but as you guys pointed out, it wasn't the best practice; not by a long shot.
1) You'd need a small server-side PHP script that accepts the new JSON file sent by the client
2) Browser requests merchants.json from the server
3) Load it with JSON.parse()
4) Add the merchant to the Object
4) JSON.stringify(object)
5) Send back to the server.
Now, this is a horrible horrible idea. Use a server-side database for storing any kind of information on your clients -- MySQL, whatever. JSON is for transporting data, not storing it. You can write some PHP scripts to dynamically generate a page for your merchant based on the data in the database -- so much easier and so much more secure. The method above will expose the whole client database to the client, and based on your specifications above, I don't see another way.

Getting data using RESTful and backbone.js

I've been reading tons of tutorials, I really like this technology, but I am missing something.
Following this tutorial http://www.youtube.com/watch?v=FZSjvWtUxYk you get JSON data from this url, http://backbonejs-beginner.herokuapp.com/users then you set your model, and collection.
I am not sure how to set this url on my own (for either local storage or database storage), I obviously need to set it to where I can GET the data or PUT/POST/DELETE data. I need to mention that I dont want to use PHP to send the data to the database, because this is a cordova app. Maybe setting data is beyond just using a URL, hopefully some one can make this clear, this should be easy points for most.
I am missing something easy here, because there is a reason they are not covering this topic extensively (maybe they are and I am overlooking it), but oh well ill ask anyways maybe someone can point this out :)
Here is the ajaxPrefilter it kind of confuses me, I know it obviously prefilters our url to point to the data, but I am not sure how to apply an appropiate url for local storage/server side.
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
options.url = 'http://backbonejs-beginner.herokuapp.com' + options.url;
});
Edit: Also I noticed that when I run a POST request, this url changes http://backbonejs-beginner.herokuapp.com/users and adds my data, this is from the RESTful services right, and what is so special about that url that it allows me to do that? In the meantime I am going to keep rewatching the backbone tutorial videos, to see what I am missing lol.
Also watching this http://net.tutsplus.com/tutorials/javascript-ajax/understanding-backbone-js-and-the-server/ starting from the beginning he actually understands what I mean, but jeffery uses PHP, which maybe I can use with cordova (pointing to a script or something) but I would rather use javascript to send data to mysql and local storage.
EDIT: Okay I see heroku is a cloud based service https://www.heroku.com/ so inside that url we were using a dummy type of service to store the data.. Okay so now how do I point the url to local storage?
Finally got it!
I came across this Backbone.js + Java Wine Cellar Application. It is an application with a Backbone front end and a Java backend. You have just to download it, set up the environment and see how it works.
There is also a tutorial, the author wrote it also in PHP, just check his blog.
Okay, so I am a noob, I am sure the way I asked this question may have gotten confusing but here is what I did.
I spent a good amount of time figuring out how to use https://github.com/jeromegn/Backbone.localStorage what I learned is, models and collections are well models and collections of data. I didn't think of it like that(should have been transparent from the get go, but oh well) inside the model and collection you need some data and so from the tutorial I followed the method of getting data was via http://backbonejs-beginner.herokuapp.com/users it contained jSON data which we could work with.
So in using local storage, we need to change where our jSON data is by using localStorage: new Backbone.LocalStorage("choose-some-identifier"),
So understanding the model and collection really helps in knowing what to do. Now I just need to figure out how to add localstorage data to a server, and since I am using phonegap it would be cool to add an event listener for when the user connects to the internet and on that event submit the local storage data to the server.

best way to send JSON to the page at creation time

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.
Been a few years since this was asked, but for anyone else who finds themselves here and curious, I've been doing a variation of option #1 for quite a while. Additionally, Nike Plus does this as well. When the page loads, Nike sets window.np = {}
I've never really found a convention I love, but I've tried:
window.data
window.app.data (inspired by Symfony, literally uses the attribute app)
window.[app_name].data (inspired by Nike Plus)
window.initData (inspired by Google+)
In my case, I overwrite these JS objects with Backbone models/collections when the main Backbone app loads.

Categories

Resources