In my view, the question is about using javascript to do PHP work. A request made with ajax can return data formatted in back-end
or may receive a json
and format for composing a view. My answer is based on this assumption.
I will give as an example a simple request containing an array of 2 indexes, only name and surname and formats in JSON, XML and HTML for comparison purposes only.
DATE
array( array( 'Papa' , 'Charlie' ) , array( 'Papa' , 'Charlie' ) )
JSON
LENGTH : 39
STING : [["Papa","Charlie"],["Papa","Charlie"]]
XML
LENGTH : 191
STING : <usuarios>
<usuario><name>Papa</name><lastname>Charlie</lastname></usuario>
<usuario><name>Papa</name><lastname>Charlie</lastname></usuario>
</usuarios>
HTML
LENGTH : 66
STING : <div>Papa</div><div>Charlie</div><div>Papa</div><div>Charlie</div>
An output in HTML will use the server to process the data, and you can display the data using simple functions. It may be the best option when there is little data flow or for those who are not so familiar with javascript. On the other hand, we have a larger data stream and can make the application more trapped.
Data in JSON are easy to work with type object
, besides having a much smaller length than the other formats, and this is an interesting point for bandwidth saving. JSON and XML are more flexible and simple to implement webservices, apps, desktop, mobile devices...
I couldn’t find a benchmark of respect that I could use as a comparison effect, but I don’t see such a drawback in the processing time between PHP and javascript as a decisive factor for change. In fact PHP consumes more resources to assemble HTML, while javascript composes at low cost. But to answer which to use or when, depending on the need - reduce traffic, make application more flexible to other platforms... I think are points of greater importance in choosing.
Some interesting references
• Why is it a bad Practice to Return generated HTML Instead of JSON? Or is it?
• AJAX - Using JSON vs echo HTML
• Why do Facebook, Twitter and Gmail render all their data to the browser as JSON as opposed to HTML?
• PHP vs Node.js: The REAL statistics
• The AJAX Answer: XML, HTML, or JSON?
• Creating HTML: PHP server-side vs. jQuery Clie
That’s a question I’ve been asking myself, especially with Infinite scroll to make javascript assemble the elements. But have the composition outside the view makes me a little uncomfortable. I look forward to a Bench on the topic.
– Papa Charlie
I believe that the answers are coming out a bit of the scope of the question which is not about the amount of requests, validation before or after, etc... Giving my opinion, turned to the question, I believe that js can be, to some extent, used as your view (separate from the server). All the logical part and the business rules would remain on the server, but who processes the interface part, who organizes the information to display to the user, would be the js.
– Oeslei