Load ajaxdata in HTML or JSON-format? - php

What's a better practice? Load data in HTMLformat or JSON-format? When I load HTML i'm able to keep all the html in my php view-file. When i load JSON I have to put it in html elements clientside with javascript.
I know that a 'best-practice-question' isn't suitable for stackoverflow. So a better answer to my question is a list of benefits and disadvantages of both techniques.

I'd say use JSON whenever you need to process the data client-side, use HTML when you just want to dump it into some container-div.
For example, consider an image viewer, you can fetch a list of preview-image-urls using JSON, create a list of images client side and display them, scroll them around and so on.
On the other hand, if you're performing some action using ajax, and you just want to display a status message (like your table of data in the popup div), I'd suggest rendering the HTML on server side and just display it.

If you plan to call the data often in the same session, the network traffic and the responsiveness will be better if you just call JSON data. The HTML/JS overhead being in the cache, only data will cross the network from the second call.
However it looks you just need to render a table with TRs/TDs. If you don't call it often, you're better off with a simple HTML dump.
Another consideration is about clearly separating the data and the view, for cleaner code and easier maintenance. A JSON call allows a clear separation between data and HTML. In an HTML dump both are mixed.
I've just answered to another question, it was for JSP, but that may interest you.
What is the best approach for handling a complex form in html?

If you later have to do a mobile version, or another client in general, you might benefit from using JSON all over. JSON will also be smaller (might matter or not, depending on your html, the amounts of elements, ...)
Here's a good article on the subject: http://www.quirksmode.org/blog/archives/2005/12/the_ajax_respon.html

Related

Return HTML in PHP JSON response

I am building an app to save small notes and comments.
The app will require from you to submit a title and it will provide you a text area for your text.
Until now when you submit a title I create with jquery a title - text area pair for you to type your text.
I was thinking to return the pair through JSON, but someone told me that this is bad practice.
Is it really bad practice to return HTML through Jason and why?
JOSN was made to overcome the bulky XML format used for data exchanging.
It really is a light weight data-exchange format as described by James.
Suppose: You need to display a dynamic list of products having all the info related to a product. If you return full HTML in the JSON its size is 2048 characters. But if you only return product name and realted info without the HTML markup then the response text string size will be less than 2048 characters, it can be 100 characters only because you are omitting the HTML markup which is not really required.
SO you can just have the light-weight version of the data and then insert it in the HTML markup using client side script. This will make your application faster because you will have to wait less for the server response as the data size is small and transferring small amount of data(characters) will always be quicker than large data(characters).
XML contained heavy markup therefore JSON was looked as an alternative for faster data transfer.
JSON (JavaScript Object Notation) is a lightweight data-interchange format
http://www.json.org/
The HTML DOM structure should be created and use JSON for exchanging data.
Once you've retrieved the data creating dynamic dom elements is fair game.
A few closely related questions:
Why is it a bad practice to return generated HTML instead of JSON? Or is it?
How dangerous is it send HTML in AJAX as opposed to sending JSON and building the HTML?
As far as I know, it's not bad practice to return a HTML string within a JSON object. The accepted answer for that second question seems to agree:
Request and return JSON for large datasets, but include the (escaped)
HTML snippet for each record in the JSON record. This means more
rendering time and more bandwidth use than (2), but can reduce
duplication of often complex HTML rendering.
It really depends on how you plan to implement your idea. As you mentioned JSON, my best guess is you are trying to implement AJAX. Well, while it's possible to return almost any type of content encoded as a JSON object, I don't see why you would need to send HTML elements like text-area from the server through JSON. AJAX is used for scenarios where a server request is made and the client wants to get the response without refreshing the page from which the request was sent. The most common usage is username and password validation on login pages.
I think you should get a clear picture of server-side scripting and client-side scripting. What you have already implemented using jquery is known as client-side scripting and that's exactly how it should be done. As for fetching data from PHP, that's done when you need to read some data from the database residing on the server. Say, the text-area is displayed only if a valid title, that has an entry in the database, has been entered. And I don't see any requirement of that here.

php creating DOM element and sending with ajax

I just started writing server code (php), I finished the client side with javascript and html. I have some questions that I hope to get some clarification on before I start coding the server side.
Is it possible/a good idea to create DOM elements (img, p, header etc) on the server side (php), send it to the client side via AJAX, client side set some extra attribute and 'attach' it (the received DOM) to a div on that html page?
I want this because those DOM elements will be used on multiple pages.
Is it possible, and if possible, is sending the entire DOM efficient?
When sending raw HTML rather than JSON you want to consider things like:
the size of the request is going to be bigger. JSON is much more succinct
the time to render the element is going to be shorter (no need to parse the JSON and render the HTML, you're already done it server side)
reusability and caching is pretty easy. Indeed, The same snippet could be served to multiple clients and the template can be cached (the same is true if you used precompiled template in JS, but it's slightly more complex).
Code logic is all in one place (server side) or in two places (JS and server side).
The recommended way to accomplish what you want is using a Template Engine, which out there are plenty of them.
This way you can have separate files for the templates and load them as necessary via an AJAX request.
I recommend you the use of Handlebars, its pretty simple and you can use it with JavaScript and also with PHP itself!!!
See the PHP Handlebars port here: https://github.com/XaminProject/handlebars.php

Insert database data into Google charts?

I'm thinking about going with Google charts for a project I'm working on. I have all my data on my own server and so I was wondering what is the best way to go about inserting this data into a chart, there are a few alternatives:
Create the DataTable object from data that is provided inline. That is, print all the data into the HTML document. This will crowd out everything else since I have a lot of data, but I don't know if this is important. This way we can avoid one HTTP request.
Dynamically create a .js files for every request, holding the data, and letting it be included with a script tag in the document.
Retrieve the data using ajax (Google suggests this in their documentation)
Using the chartwrapper and adding a datasource pointing to my own server. This would be equivalent to the above, I suppose, and functionally equivalent to (2).
So what is the most common solution? What do you usually solve this?
I wouldnt worry about crowding out your data. Printing it out into a javascript datatable wont be visible to the user, and the browser wont care. However I would suggest you only print out what you need for each page so you dont have more than required.
I think probably any of your solutions are fine, so pick the one that suits you best.

Displaying database content - PHP vs Javascript

I am (mostly) a front-end developer working on a prototype with a backend guy on a site. The basics of it would require a user login area, as well as a search form that would search and return results from a database table.
He is doing the backend logic with Java and PostgreSQL. He proposes to return a JSON format to me upon a query. This means I will have to take the data from the JSON string and populate/create the HTML markup. I can do this with either Javascript, or PHP. It seems to be that PHP would be a no brainer as I don't need to create HTML markup with Javascript/jQuery and also all the data populated by the server already, reducing the load on the client side, but this means as a "front-end" person I am also writing PHP.
And regarding loading all server data onto a page with Javascript, is this standard practice? Or should it only be used on AJAX?
Should the backend guy be generating the markup as well? What's the best way of separating this frontend and backend work? THanks!
If you are using PHP, you are a backend-guy, too.
If the markup is generated by the server, than you would usually not write an AJAX-application, because the markup is generated by the server.
In fact if you want to write a ajax-application, you have to manipulte the DOM with Javascript. Use jQuery or something like that to do this.
Seperating frontend and backend is done by creating an Interface, a contract which will separate the UI from the Backend-Logic. In your case the contract is the format of your JSON Data.
A good compromise would be to do either:
Option 1
A small PHP script server-side which formats the restults into a table with appropriate Ids/similar to allow javascript to add classes for styling. This entire table could be returned via an AJAX call and placed within a placeholder div on the page.
Option 2
The server returns simple JSON to the front-end, the front-end uses whatever mechanism it sees fit to build the appropriate HTML
The first one is a little cleaner to code - The generation of the HTML is seperated from the styling, but it's an extra hop (the PHP) and is slightly inflexible - the JS can modify the table as appropriate but it's limited by the html PHP sends.
The second is slightly more verbose to code but completely flexible.
I send the data from the server to the browser in JSON all the time, format on the browser with templates of one form or another. I would rather work with arrays in Javascript as the array methods like map and filter make it much easier.

How to capture DOM modifications with JavaScript and send them to a PHP server

I've been asked to create a web UI that allows a user to modify a specific section of the HTML DOM and then POST the modifications back to the server for storage. The modification should be done via drag'n'drop, with my tool of choice being jQuery. The server will be PHP, but written by someone else since I'm not a PHP programmer.
The only way I can think to do this is to send back to the server the entire DOM section via AJAX whenever it is modified. However, that is expensive since the section could be quite large. Furthermore I'm not sure how I'd efficiently capture the modified section and write it to a string which can be sent to the server. Overlapping events would also be a big concern.
Any ideas for a better approach? Are there libraries/tools (JavaScript or server-side) that I should be considering? Many thanks.
Well if you are dealing with some list of elements, say rows in table you can send back a map where particular row is mapped to a position then when you re-initialize the page you can feed such map back and rearrange the list.
Also - another idea (since you are using PHP) you can have some sort of a model on the back end which backs your visual DOM element, then again - you send back some parameters you have changed (order, size, etc.) and adjust/save the model
Instead of sending the entire DOM section you should try to serialize the DOM section you're sending to something more lightweight (like JSON). Since it's HTML, serializing it to JSON will dramatically reduce it's size.
Apart from that I think there's not much you can do besides some AJAX request to allow the server to save the changes.
You'd want to use something like the UI plugin to facilitate the actual dragging/dropping/reorganizing. I don't know of any libraries that will pick out DOM objects and AJAX information to a server in a particular fashion, so you would probably have to code something like that yourself to suit your specific needs. It might help to know what sort of DOM node you're trying to send.
If you're building something like a custom WYSIWYG, sending the entire node might be the best approach without losing information. If you're doing something simple like allowing users to drag and drop to reorder a list something like the following code might suffice:
var toPost = '';
function handler(data) {//handle server response}
$("ul#container li").each(function(){toPost+=this.getAttribute('rel');});
$.post('processing_script.php',{data:toPost},handler);
I checked into how Google handles these. If you drag and drop an element on the iGoogle homepage, a GET request is sent to the Google handling script with the following parameters:
et '4af26272PQUMZP8V'
mp '19_1:4_1:7_1:13_1:16_1:18_2:2_2:3_2:14_2:11_2:_opt_3:17_3:6_3:12_3'

Categories