What is best practice for firing AJAX calls along with page load?
In more detail - I have a view responsible for rendering model’s view details (clicking View in CGridView) where I put models data right in the top of the page in CDetailView, but I would like to add two or three more sections on that page (headers) and would like to fire AJAX call for each of that section to bring up additional data just as page finishes load.
It was planned this way, as we are using slow connection to DB and we want user to be presented with any basic data (that comes from model) while he can visually see that additional data is being loaded as he reads basic one. This is why we decided to do this like that, inplace of preloading everything in controller and putting it directly to view.
My question is what to use to have AJAX call attached to page load event? Register own script via using CClientScript or what?
And another question, related - what is the best practice for drawing loader for above mentioned content? Is it to put an empty div with class making his background animating with some progress and renders in a view some text like Loading and when successful AJAX response comes back to change that div’s class to non animated one and change text to response? Or maybe to put image to loader directly to the div, before text and replace whole thing with AJAX response - i.e. not playing with styles or classes?
All right, I got it working. I put a complete solution here for future reference, maybe I’ll save someone time.
As I wrote, I want this AJAX request to be fired when page finishes loading. With a little help from the both post (this and the one, I mentioned), I was able to mange this with such code:
Where #section_2_div is an element that should be updated with results of AJAX request and proper part in the controller can look like this:
class ZleceniaController extends Controller
{
public function actionAJAXGetParams()
{
if(app()->request->isAjaxRequest)
{
echo date('H:i:s'); //Echo out what you want to return as request's result
app()->end();
}
else throw new CException('Operation requires AJAX request!');
}
}
Yeah! That just another, maybe better, approach. I wasn’t just sure if it is good idea to use registerScript in a view. But probably, it is OK. Thanks!