I’m always trying to find new methods on development. So I looked into some websites and analyzed their ways of presentation.
-
Returning part of the page using AJAX
Normally I will use an array to return values, for example:
//GET User details $user_id = $_POST['user_id']; $user_details = $this->get_user($user_id); if ($user_details['status'] == true) { exit(json_encode(array('status'=>true, 'data'=>$user_details['data']))); } else { exit(json_encode(array('status'=>false, 'reason'=>'SomeReasons....'))); }
But I see that some sites returning `HTML’. Is this preferable in any reason?
Also what is the best method to use: AJAX
or an iframe
?
I don’t necessarily agree entirely with Tom’s answer so I’m going to give my opinion.
Generally, you should avoid returning XHTML and instead return JSON, transforming the result into the DOM using JavaScript and your framework of choice.
There are some situations such as returning very large amounts of data where this isn’t just not practical, but you end up duplicating your presentation in both JavaScript and in the initial renderer. An example of this recently for me would be a reporting part of an application I was working on. I had the service endpoint configured to return XML data, for the web site I created an adaptor to transform the data with and XML stylesheet and return the XHTML. You could of course return XML to the browser and run the XSL client side.
In summary, generally return JSON however there are appropriate times, in my opinion, to return XHTML, and this is the reason as you say you see it online in places.
Use of an iframe
is an “old fashioned” way to update part of the page without a full refresh. This is not the same effect as AJAX as most browsers will now days restrict programmatic access to the DOM of the iframe
, so from that you can infer Ajax is the correct way to do it.
It’s always better to return JSON rather than HTML in your AJAX result. By returning HTML you’re letting your presentation layer leak into your data layer.
Generally speaking you should use AJAX rather than iFrames since its a neater solution and allows bookmarking (if you set it up). There are some use cases where iFrames are appropriate, for example when you need data from another site. For further reading have a look here and here.
2