Bootstrap 3.1 load tab content using ajax (external view) on laravel 4.1

Ok now I want create a tutorial about how to load external view using ajax on laravel. Okay we just started the tutorial. 🙂
The first, I assume You have to install the laravel framework. If not, You can follow from this link http://laravel.com/docs/installation, after that, now I assume you have download Bootstrap from twitter and latest jquery from this site. http://getbootstrap.com/ and this http://jquery.com/. Ok after all has been downloaded, now open your laravel framework on your editor text.
Okay the first paste all jquery and bootstrap to public/assets like this:

And then, create file on your app/views with name home.php and fill the code like this:

<!DOCTYPE html>
<html>
<head>
	<title>Example Bootstrap Tab</title>
	<!-- Css -->
	<?php 
		echo HTML::style('assets/css/bootstrap.min.css');
		echo HTML::style('assets/css/bootstrap.css.map');
		echo HTML::style('assets/css/bootstrap-theme.min.css');
		echo HTML::style('assets/css/bootstrap-theme.css.map');
	?>
	<style type="text/css">
		body {
			margin: 20px;
		}
	</style>

	<!-- Jquery -->
	<?php 
		echo HTML::script('assets/js/jquery-2.1.0.min.js');
		echo HTML::script('assets/js/jquery-2.1.0.min.map')
	?>
</head>
<body>
<h1 class="bg-primary center">Bootstrap Tab With External View</h1>
<div class="row-lg-12">
	<!-- Tab Attribute -->
	<ul id="myTab" class="nav nav-tabs">
      	<li class="active"><a href="#home" data-toggle="tab">Home</a></li>
      	<li class=""><a href="#profile" data-toggle="tab">Profile</a></li>
      	<li class="dropdown">
        	<a href="#" id="myTabDrop1" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        	<ul class="dropdown-menu" role="menu" aria-labelledby="myTabDrop1">
          		<li><a href="#dropdown1" tabindex="-1" data-toggle="tab">@fat</a></li>
          		<li><a href="#dropdown2" tabindex="-1" data-toggle="tab">@mdo</a></li>
        	</ul>
      	</li>
    </ul>

    <!-- Tab Contents -->
    <div id="myTabContent" class="tab-content">
      	<div class="tab-pane fade active in" id="home">
        	<p>Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.</p>
      	</div>
      	<div class="tab-pane fade" id="profile">
        	<p>Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.</p>
      	</div>
      	<div class="tab-pane fade" id="dropdown1">
        	<p>Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.</p>
      	</div>
      	<div class="tab-pane fade" id="dropdown2">
        	<p>Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.</p>
      	</div>
    </div>
</div>

	<!-- Bootstrap and Custom Script -->
	<?php echo HTML::script('assets/js/bootstrap.min.js'); ?>
	<?php echo HTML::script('assets/js/custom.js'); ?>
</body>
</html>

This is a sample tabs using bootstrap 3.1. And then open your controller and create file HomeController.php on your app/controllers. And write code like this:

<?php

class HomeController extends BaseController {

	/*
	|--------------------------------------------------------------------------
	| Default Home Controller
	|--------------------------------------------------------------------------
	|
	| You may wish to use controllers instead of, or in addition to, Closure
	| based routes. That's great! Here is an example controller method to
	| get you started. To route to this controller, just add the route:
	|
	|	Route::get('/', 'HomeController@showWelcome');
	|
	*/

	public function show()
	{
		return View::make('home');
	}

}

And the last is your change your app/routes.php:

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

Route::get('/', 'HomeController@show');

And now run your project. And this is the result:

And now is implement using database. Note: This is a sample database structure from me, so you can implement with your database too 🙂

MariaDB [spk_sman28]> select * from criteria;
+----+------------+---------------------+---------------------+
| id | name       | created_at          | updated_at          |
+----+------------+---------------------+---------------------+
| 31 | Matematika | 2014-03-07 14:44:50 | 2014-03-07 14:44:50 |
| 32 | Biologi    | 2014-03-07 14:44:53 | 2014-03-07 14:44:53 |
| 33 | Kimia      | 2014-03-07 14:44:55 | 2014-03-07 14:44:55 |
| 34 | Fisika     | 2014-03-07 14:44:57 | 2014-03-07 14:44:57 |
| 35 | Ekonomi    | 2014-03-07 14:45:09 | 2014-03-07 14:45:09 |
| 36 | Geografi   | 2014-03-07 14:45:11 | 2014-03-07 14:45:11 |
| 37 | Sosiologi  | 2014-03-07 14:45:15 | 2014-03-07 14:45:15 |
+----+------------+---------------------+---------------------+
7 rows in set (0.00 sec)

And this:

MariaDB [spk_sman28]> select * from suitability_rating;
+----+-------------+-------+------+------+---------------------+---------------------+
| id | criteria_id | value | ipa  | ips  | created_at          | updated_at          |
+----+-------------+-------+------+------+---------------------+---------------------+
| 33 |          31 | 30-59 | 0.25 | 0.25 | 2014-03-07 23:33:38 | 2014-03-09 11:23:00 |
| 34 |          31 | 60-69 |  0.5 |  0.5 | 2014-03-07 23:33:38 | 2014-03-09 11:19:06 |
| 35 |          31 | 70-79 | 0.75 | 0.75 | 2014-03-07 23:33:38 | 2014-03-07 23:33:38 |
| 48 |          31 | >80   |    1 | 0.75 | 2014-03-09 11:23:10 | 2014-03-09 11:23:10 |
| 49 |          32 | 10-59 | 0.25 | 0.25 | 2014-03-09 11:25:53 | 2014-03-09 11:25:53 |
| 50 |          32 | 60-69 |  0.5 |  0.5 | 2014-03-09 11:26:49 | 2014-03-09 11:26:49 |
| 51 |          32 | 70-79 | 0.75 |  0.5 | 2014-03-09 11:26:49 | 2014-03-09 11:26:49 |
| 53 |          32 | >80   |    1 |  0.5 | 2014-03-09 11:38:55 | 2014-03-09 11:38:55 |
+----+-------------+-------+------+------+---------------------+---------------------+
8 rows in set (0.00 sec)

And now the question is how to implement bootstrap tabs with external view?
And this is an answered from me, so the first we must change the controller like this:

public function show()
	{
                /*get data from table criteria*/
		$criteria = DB::table('criteria')->get();
		return View::make('home')->with('datas', $criteria);
	}

Explanations:

  1. Line 21 is to get all data from table criteria
  2. Line 22 is to send last data and send to view with parameter is datas.

So now open your view, and example I change like this:

<!DOCTYPE html>
<html>
<head>
	<title>Example Bootstrap Tab</title>
	<!-- Css -->
	<?php 
		echo HTML::style('assets/css/bootstrap.min.css');
		echo HTML::style('assets/css/bootstrap.css.map');
		echo HTML::style('assets/css/bootstrap-theme.min.css');
		echo HTML::style('assets/css/bootstrap-theme.css.map');
	?>
	<style type="text/css">
		body {
			margin: 20px;
		}
	</style>

	<!-- Jquery -->
	<?php 
		echo HTML::script('assets/js/jquery-2.1.0.min.js');
		echo HTML::script('assets/js/jquery-2.1.0.min.map')
	?>
</head>
<body>
<h1 class="bg-primary center">Bootstrap Tab With External View</h1>
<div class="row-lg-12">
	<!-- Tab Attribute -->
	<div class="row">
        <div class="col-lg-12">
            <ul id="ratingTab" class="nav nav-tabs">
            <?php foreach($datas as $data): ?>
                <li><a href="#<?php echo $data->id ?>" data-toggle="tab"><?php echo $data->name ?></a></li>
            <?php endforeach; ?>
            </ul>
            <h2 style="text-align: center">Inserts Rating</h2>
            <div id="ratingTabContent" class="tab-content"></div>
        </div>
    </div><!-- /.row -->

    <div class="row">
        <div class="col-lg-12">
            <button type="button" class="btn btn-success" id="addRating">Add</button>
            <input type="submit" class="btn btn-primary" value="Save All" id="rSave" />
          </div>
    </div>
</div>

	<!-- Bootstrap and Custom Script -->
	<?php echo HTML::script('assets/js/bootstrap.min.js'); ?>
	<?php echo HTML::script('assets/js/custom.js'); ?>
</body>
</html>

And now run this code. And now I have result like this:

See, from above picture the tab is automatically create with data from database. See table criteria from above code.
Okay now we must create custom.js for ajax external view using jquery. Create this file on public/assets/js/custom.js and write this code:

$(function () {

    /* Add class active to first li content */
    function tabContent(event) {
        /* getting id */
        var criteriaId = event.target.hash.substr(1);
    }

    /*load content if clicked*/
    $("#ratingTab li:first").addClass("active");
    if($("#ratingTab li:first").hasClass("active")) {
        setTimeout(function(){$("#ratingTab li a:first").trigger("click");},800);
    }

    /* Rating Tabs */
    $(document).on("click", "#ratingTab li a", tabContent);

});

Explanations:

  1. Line 4 is a custom function, so this function is used on line 16
  2. Line 6 is to get id from each tab (see home.php line 32) and from this code href=”#<?php echo $data->id ?>”. So if we see on console.log or if add console.log(criteriaId) under line 6, so we can get result like this:

    See in right pane. We get id like 31,32,33 and etc.
  3. Line 10 is after document ready and load all content, so add class active for the first tab. This is useful for automatically select first tab.
  4. Line 11 is bad code for me.. 🙂 so after I add class to first tab, I call/trigger line 16
  5. Line 16 is used if we click the tab. Example from line 6, if we click first tab we get id 31, and if second tab we get id 32 and so on.

From the above we only create code to get the id, so for load content external, first we must create another view to use if content is calling. So on app/views we add file external.php

<div class="col-lg-12 ratingTable">
    <table class="table table-hover">
         <thead>
            <tr>
                <th width="5%">No</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Tab ID</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <input type="hidden" name="criteriaId" value="{{{ $criteriaId }}}" />
            <tr>
                <td class="form_code">1</td> 
                <td>Imron</td>
                <td>Rosdiana</td>
                <td><?php echo $criteriaId ?></td>
                <td><a href='#'><i class='fa fa-trash-o delRating'></i></a></td>
            </tr>
        </tbody>
    </table>
</div>

Explanation:Line 18 is used to display the id number corresponding tab is clicked
And we must change Home.php to be like this:

    <div class="row">
        <div class="col-lg-12">
            <button type="button" class="btn btn-success" id="addRating">Add</button>
            <input type="submit" class="btn btn-primary" value="Save All" id="rSave" />
          </div>
    </div>
</div>
    
    <script type="text/javascript">
        var page = "<?php echo URL::to('/'); ?>"
    </script>

Explanation: Line 49 is used for refer to custom.js
And this is the change of the file custom.js

$(function () {

    /* Add class active to first li content */
    function tabContent(event) {
        /* getting id */
        var criteriaId = event.target.hash.substr(1);
        
        /* Call ajax to external view */
        $.ajax({
            url: page,
            type: "GET",
            data: "criteriaId=" + criteriaId,
            success: function (data) {
                $("div#ratingTabContent").html(data);
            }
         });

    }

    /*load content if clicked*/
    $("#ratingTab li:first").addClass("active");
    if($("#ratingTab li:first").hasClass("active")) {
        setTimeout(function(){$("#ratingTab li a:first").trigger("click");},800);
    }

    
    /* Rating Tabs */
    $(document).on("click", "#ratingTab li a", tabContent);
});

Explanations:

  1. Line 9 is jquery ajax functions. See in this site https://api.jquery.com/jQuery.ajax/
  2. Line 10 is the reference url (see on home.php line 49)
  3. Line 11 is type send data, example I get on php we know with $_GET.
  4. Line 12 is I send data with name criteriaId and the data is the data obtained on line 6 (var criteriaId)
  5. Line 13-15 is the function if sending data is succes, so if succes sending, add the external view (external.php) to tab content.

Then to get external view from ajax request, we must change the controller like this:

	public function show()
	{
        if (Request::ajax()) {
            /* getting id */
            $criteriaId = Input::get("criteriaId");
            return View::make('external')->with('criteriaId', $criteriaId);
        }
        /*get data from table criteria*/
		$criteria = DB::table('criteria')->get();
		/*send data to view*/
		return View::make('home')->with('datas', $criteria);
	}

Explanations:

  1. Line 20 is if the function get request from ajax so run the code in it (see custom.js line 9-16).
  2. Line 22 is to get criteriaId because we send id using ajax (custom.js line 12)
  3. Line 23 is to call view (external.php) with data name criteriaId for used in external.php line 18

And finishing run the project again, and we should be getting results like this:

3 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s