Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for returning and displaying data from AJAX calls

I have some jquery/php interaction set up on a page. It submits some data to the server and gets back records of data which are then to be aligned on the page for comparison and possible action beyond that.

My question is what is the best practice for returning the info and then displaying it?

  • Return JSON object and then create html on the fly with js and display the data?
  • Return JSON object and then put that data in already created containers for the data on the page?
  • Return pure html from the server and just put that on the page?

I was rolling these through my head last night and couldn't really figure out if one way would be better for any particular reason.

I'm not a js guru so wasn't really sure the pros/cons and caveats to these different methods.

like image 656
Nathan Hess Avatar asked May 20 '09 20:05

Nathan Hess


3 Answers

I think it ends up depending on your app.

Pure HTML is the easiest, you just drop in in place and viola. JQuery makes it a breeze to add the proper events and what not.

However, whenever I've used AJAX it's always evolved into returning JSON and building elements on the fly. If you are populating a tree for example, it may become messy to get the proper nesting. This forces you to have to do client side code anyway at which point simply using JSON from the start is cleaner.

Also, If you plan to use the data calls from other pages then using JSON is the way to go because the HTML will bee fixed.

like image 130
Tom Hubbard Avatar answered Sep 23 '22 09:09

Tom Hubbard


This completely depends on the way you have things set up in your application. I, for one, prefer to return JSON (second approach in your list), because I have an 'error code' parameter that I check in onSuccess function before updating the content on the page, and if it's not zero then I notify the user of the error, including the error message that came back from the server (server-side validation, database timeout, etc.).

like image 44
montrealist Avatar answered Sep 22 '22 09:09

montrealist


The "possible action beyond that" part of your question makes a big difference. If you need to do other things with the data besides display it, returning as JSON is a clearly better option because you can work with the data as a native JavaScript object instead of having to traverse the HTML DOM. If all you ever intend to do is display it, I don't see any reason to go through the trouble of building that display in JavaScript; just build the HTML in your presentation layer on the server.

like image 29
John M Gant Avatar answered Sep 19 '22 09:09

John M Gant