I have read in many places that it is best practice to use ajax to retrieve JSON and not HTML.
I understand that the reasoning behind it is it being slightly faster, and having the option to do more with the raw data rather than retrieving html.
But i haven’t been able to find good examples that explain clearly how to actually convert the JSON data in to the desired HTML output.
For example, i have a like button:
<form action="/reactions/save" method="POST"> <button type="submit"> <i class="fa fa-thumbs-o-up" aria-hidden="true"></i> 3 </button> </form>
What this shows is a thumbs up icon, and the amount of likes the item already has (which is 3 in this example).
What i want to achieve is to click on that button, to load the url
/reactions/save with ajax, which saves the new like, and then to change the button to indicate that this item has been liked, and to change the amount of likes next to the button.
Basically the same as facebook, or any other website has a like button, the same as this site has a like button.
What i would normally do is attach that button to a jquery function that will load that url when clicking on it, the url would return the new button already formatted (it would return HTML), and i would use jquery to just replace the two buttons.
But as i read and am constantly told, it is better to retrieve JSON and to format that data in to the button.
I just don’t understand how, and if it would not be much simpler to just get the HTML from the response and output it rather than getting the JSON data, formatting it, and then outputting it.