Darek Budziasz Darek Budziasz - 1 year ago 53
Ajax Question

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 :)

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download