Return HTML in PHP JSON response - php

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.

Related

Rendering a page in PHP: How?

This may be a inappropriate question for SO, but I thought lets see :)
I'm writing a website in php. Every pageload may have 10-20 DB requests.
Using the result of the DB queries I need to generate a page.
The page would contain a topic (should be image or text) followed by comments. There could be mutiple topics like this.
Currently, I'm creating a string using the DB result and sending it to the browser.
When browser receives the string (as an ajax response), it parses using split functions and creates the HTML dynamically.
I'm basically a C++ programmer; relatively new to web development. So, I do not have fair understanding of the JS objects. How long of a string can JS variable hold? Is it ok to use split and generate HTML at the client.
I'm not generating the complete HTML at the server side to avoid any overhead because of string concatenation. I believe sending less no. of characters to the client (like I'm doing) is better as compared to sending complete HTML code.
Is something (or everything) wrong in my understanding :)
Any help is appreciated.
EDIT:
Well, I'll be highly grateful if I could get opinions in yes/no. What would you recommend. Sending HTML to the client or a string that will be used at the client to generate HTML?
Unless you have a specific reason for doing so, I think you should look into generating the HTML with PHP and sending it directly to the browser. PHP was built specifically for this purpose.
I think you be best off to look at jQuery and more specific to the AJAX method of that library. Also, take a look at JSON and you should be all good to go.
Have you considered using a templating engine like Smarty?
It's pretty simple to use, take a look at the crash course, you might like it! http://www.smarty.net/crash_course

Json vs Standard Post

I have developed a free shopping cart plug-in for small websites, I am currently using name=value&name=value to submit items to the basket.
The process is html form -> jQuery serialize -> AJAX post -> php,
I have read that JSON is a more secure way to pass this data. I was hoping some kind person could explain to me why this is or point me to any web resources on the subject.
JSON posted with XHR is no more (or less) secure than any other request.
They all must be handled appropriately.
There's no difference between AJAX POST or any other POST. It's all the same.
HTTP is a simple protocol, whether JavaScript sends headers or a custom built script - it doesn't matter to the underlying server since all it sees is plain text that it interprets.
There's no "more" security if you use AJAX or regular POST-ing, anyone can send any sort of data to the target script so you need to handle it properly.
It's not related to security at all.
JSON is just a different way to transmit the data - instead of posting a querystring-like string you send a string that is valid JSON.
By default in AJAX, data is posted in xml format using some protocol. while parsing data from xml format, we will get all node values in string format. Hence data type of the value submitted/received is not known. If required we need to typecast the data.
where as in JSON format data types has been persisted till some extent.
POSTing JSON data requires that certain types of headers be sent back and forth between the client and server. For instance, the client needs to send content type, the server needs to respond with allow-options for content type and access origin. POSTed JSON doesn't come through the PHP $_POST variable, rather it is carried in $HTTP_RAW_POST_DATA.
Without the proper headers, a browser kills the response and its data, preventing the page from looking at or processing anything. Or at least, it's supposed to.
Is generally more "secure" for preventing cross site scripting problems, but the data and calls are still subject to hacking the posted data and headers and such.

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.

Load ajaxdata in HTML or JSON-format?

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

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