Darek Budziasz
Darek Budziasz

Reputation: 98

Which way for ajax response is better?

I thinking how I can design response to frontend part of website.
I want to know which solution and why is better ?

  1. Response as html
  2. Response as json

To back-end side I using PHP with template engine TWIG. To front-end side I using jQuery. To front-end I don't use any template engine.

I won't use template engine for back-end and front-end side, bacause I will have to duplicate template . It seems for me bad solution. Or maybe should I do it in this way ? maybe exist template engine which are able to use it in both case ?

Please could someone me advise ?

English is not my native language, so sorry if it hard to understand. I believe someone will know what I mean :)

Upvotes: 1

Views: 50

Answers (2)

Asperitas
Asperitas

Reputation: 329

There's no better solution. I myself prefer all my ajax calls to return JSON because I can just let the front end determine what to do with it. This way I'm maintaining separation of concerns. But like I said, it's a personal preference. Outputting HTML isn't considered bad practice per say.

I'm not sure what you mean by back end templates and front end templates though.

Upvotes: 1

lleaff
lleaff

Reputation: 4319

JSON will be "better" in the vast majority of cases.

  • The information transferred from the server will be smaller. Consider: ["john","clara","paul"] vs <ul><li>john</li><li>clara</li><li>paul</li></ul>

  • Your back-end will be more flexible in how it can be used, you will be able to update your front-end markup independently of the back-end. JSON is also easier to manipulate with JavaScript than HTML.

The only exception to this is if you want to hide the logic used to generate the html from the public, but even in that case I'd favor sending JSON for the flexibility advantage.

Upvotes: 1

Related Questions