I'm developing web application using PHP with CodeIgniter MVC framework with a huge real time client-side functionality needs. This is my first time to build large scale of client-side app. So I combine the PHP with a large scale of JavaScript modules in one project.
As you already know, MVC framework seperate application modules into Model-View-Controller.
My concern is about View layer.
I could be display the data on the DOM by PHP built-in script tag by load some data on the Controller. Otherwise I could use AJAX to pulled the data -- treat the Controller like a service only -- and display the them by Javascript.
Here is some visualization
I could put the data directly from Controller:
<label>Username</label> <input type="text" id="username" value="<?=$userData['username'];?>" /><br />
<label>Date of birth</label> <input type="text" id="dob" value="<?=$userData['dob'];?>" /><br />
<label>Address</label> <input type="text" id="address" value="<?=$userData['address'];?>" />
Or pull them using AJAX:
$.ajax({
type: "POST",
url: config.indexURL + "user",
dataType: "json",
success: function(data) {
$('#username').val(data.username);
$('#dateOfBirth').val(data.dob);
$('#address').val(data.address);
}
});
So, which approach is better regarding my application has a complex client-side functionality?
In the other hand, PHP-CI has a default mechanism to put the data directly from Controller, so why using AJAX?
Ajax is used for fetching data from remote server(s) without page refresh. You can use to fetch data from servers asynchronously and hence the page will seems interactive. Your both approaches are fine and can work for you. But to explain you this, let me explain by an example.
You have page where you have 5 blocks, latest users, latest news, latest comments, recipes and offers. Each block has its own data. Now if you are using the approach to get all that data in controller and pass it to views it will work fine and will have no side effects of this approach.
On the other hand, if you use ajax asynchronous call, first the page will load, then some data loading indicator will be displayed by javascript and asynchronous calls will be made to server for all those blocks. When the data is loaded to the respective blocks, the loading indicator will be hidden. Now in this approach the page will be interactive and will look alive.
If you google, then you will find more reasons.
I hope this will help.