Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better practice? Getting HTML from Jquery Response

This is just a question as to find out what and how people do this, but

Say a user adds something to a list, when it's done, it runs the ajax below and updates the .user-stream-list

$.ajax({
    url: "user-stream-list.php",
    success: function(data){
        $(".user-stream-list").html(data);
    }
});

but the user-stream-list.phpresponse for example is

<li class='feed'><a href='http://www.theverge.com/rss/index.xml' data-fid='13' data-uid='15'><img class='favicon' src='https://www.google.com/s2/favicons?domain=www.theverge.com'><span class='title'>The Verge -  All Posts</span><span class='options'><span class='addcat' data-fid='13'>+</span><span class='delete'>×</span></span></a></li>

Would this be acceptable in web development? Or should I really be passing it through as json and sort it into html afterwards?

like image 833
ngplayground Avatar asked Jan 19 '26 05:01

ngplayground


1 Answers

Do what works for your particular problem. Good design finds compromise between the trade-offs. If you are on a tight deadline and you need something that works and it is easier to return HTML from PHP do it.

That said, you are generating the HTML programmatically on the server. You have same job if you pass JSON, the difference being the client generates the HTML. That is far more flexible for you, as you can generate different HTML in different contexts. Or not even HTML at all.

Designing to return a flexible data structure loosely couples your application components by affording reuse: the data structure remains agnostic to the caller's environment and the target presentation. This flexibility will serve your application well as it grows, and - in my opinion - the effort to design such an API early on is worth it.

like image 56
bishop Avatar answered Jan 20 '26 18:01

bishop