Link to home
Start Free TrialLog in
Avatar of Marco Gasi
Marco GasiFlag for Spain

asked on

CodeIgniter and Ajax calls for a dummy

Hia all.
I'm trying to learn by doing CodeIgniter: I need to migrate my code from a custom (weak) framework to CodeIgniter.
I'm following this tutorial: http://phpsblog.agustinvillalba.com/adding-ajax-codeigniter-jquery/
Here are my files:

Controller:
Categories.php
<?php

class Categories extends CI_Controller
{

	public function __construct()
	{
		parent::__construct();
	}
	
	public function index()
	{
		$data['title'] = 'Categories';

		$this->load->view( 'templates/header', $data );
		$this->load->view( 'categories/index', $data );
		$this->load->view( 'templates/footer' );
	}
}

Open in new window


Listcat:
<?php

class Listcat extends CI_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model( 'categories_model' );
	}

	public function index()
	{
		$data['categories'] = $this->categories_model->get_categories();
		$this->load->view( 'templates/header', $data );
		$this->load->view( 'categories/listcat', $data );
		$this->load->view( 'templates/footer' );
	}
}

Open in new window


The model Categories_model
<?php

class Categories_model extends CI_Model
{

	public function __construct()
	{
		$this->load->database();
	}

	public function get_categories( $catid = FALSE )
	{
		if ( $catid === FALSE )
		{
			$query = $this->db->get( 'categories' );
			return $query->result_array();
		}

		$query = $this->db->get_where( 'categories', array( 'category_id' => $catid ) );
		return $query->row_array();
	}

}

Open in new window


Here the views (I put here with header and footer which are dinamically added:
index for Categories controller:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
<!--    <link rel="icon" href="../../favicon.ico">-->

    <title>1Stop-HomeShop</title>

    <!-- Bootstrap core CSS -->
    <link href="<?php echo base_url('assets/css/bootstrap.min.css')?>" rel="stylesheet">

    <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
    <!--[if lt IE 9]><script src="<?php //echo base_url('js/ie8-responsive-file-warning.js')?>"></script><![endif]-->
    <script src="<?php echo base_url('assets/js/ie-emulation-modes-warning.js')?>"></script>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- Custom styles for this template -->
    <link href="<?php echo base_url('assets/css/carousel.css')?>" rel="stylesheet">
    <link href="<?php echo base_url('assets/css/frac_reset.css')?>" rel="stylesheet">
    <link href="<?php echo base_url('assets/css/frac_style.css')?>" rel="stylesheet">
    <link href="<?php echo base_url('assets/css/fractionslider.css')?>" rel="stylesheet">
    <link href="<?php echo base_url('assets/css/app.css')?>" rel="stylesheet">
  </head>
<!-- NAVBAR
================================================== -->
  <body>
    <div class="navbar-wrapper">
      <div class="header-container">

        <nav class="navbar navbar-inverse navbar-static-top" role="navigation">
          <div class="container">
						<img src="<?php echo base_url('assets/images/logomio.png')?>" alt="1Stop-HomeShop" />
              <ul class="nav navbar-nav pull-right">
                <li class="active"><a href="#">Home</a></li>
                <li class="dropdown">
									<a href="#" class="dropdown-toggle" data-toggle="dropdown">Furniture <span class="caret"></span></a>
                  <ul class="dropdown-menu" role="menu">
                    <li><a href="#">Action</a></li>
                    <li><a href="#">Another action</a></li>
                    <li><a href="#">Something else here</a></li>
                  </ul>
								</li>
                <li class="dropdown">
									<a href="#" class="dropdown-toggle" data-toggle="dropdown">Kitchen Ware <span class="caret"></span></a>
                  <ul class="dropdown-menu" role="menu">
                    <li><a href="#">Action</a></li>
                    <li><a href="#">Another action</a></li>
                    <li><a href="#">Something else here</a></li>
                  </ul>
								</li>
                <li class="dropdown">
									<a href="#" class="dropdown-toggle" data-toggle="dropdown">Lightning <span class="caret"></span></a>
                  <ul class="dropdown-menu" role="menu">
                    <li><a href="#">Action</a></li>
                    <li><a href="#">Another action</a></li>
                    <li><a href="#">Something else here</a></li>
                  </ul>
								</li>
                <li class="dropdown">
									<a href="#" class="dropdown-toggle" data-toggle="dropdown">Textiles <span class="caret"></span></a>
                  <ul class="dropdown-menu" role="menu">
                    <li><a href="#">Action</a></li>
                    <li><a href="#">Another action</a></li>
                    <li><a href="#">Something else here</a></li>
                  </ul>
								</li>
                <li><a href="#contact">Contact</a></li>
              </ul>
						<!--{__NAV__}-->
          </div>
        </nav>

      </div>
    </div>
<div class="slider-wrapper">
</div>
<div class="container marketing">

	<!-- Three columns of text below the carousel -->
	<div class="row">
		<div class="col-lg-12">
			<div class="main">
				<div id='btn'>click me!</div>
			</div>
		</div>
	</div>
</div>

    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="<?php echo base_url('assets/js/bootstrap.min.js')?>"></script>
    <script src="<?php echo base_url('assets/js/docs.min.js')?>"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="<?php echo base_url('assets/js/ie10-viewport-bug-workaround.js')?>"></script>
    <script src="<?php echo base_url('assets/js/jquery.fractionslider.min.js')?>"></script>
    <script src="<?php echo base_url('assets/js/fractionslider_init.js')?>"></script>
    <script src="<?php echo base_url('assets/js/knockout.js')?>"></script>
		<script type="text/javascript">
			var baseurl = "<?php print base_url(); ?>";
			$(document).ready(function()
			{
				var cat = [];
				$('#btn').on('click', function(){
					$.ajax( {
						type: 'post',
						url: baseurl+'listcat',
						dataType: 'json',
						success: function ( result ) 
						{
							cat = result;
						},
						error: function ( result )
						{
							alert(JSON.stringify(result, null, 4));
						}
					} );
				});
				$(function() {
					model = {
						categories: ko.observableArray(cat)
					};
					ko.applyBindings(model);
				});

			});
		</script>		
		
    <!--<script src="<?php //echo base_url('assets/js/test.js')?>"></script>-->
  </body>
</html>

Open in new window


and listcat for Listcat controller:
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
<!--    <link rel="icon" href="../../favicon.ico">-->

    <title>1Stop-HomeShop</title>

    <!-- Bootstrap core CSS -->
    <link href="<?php echo base_url('assets/css/bootstrap.min.css')?>" rel="stylesheet">

    <!-- Just for debugging purposes. Don't actually copy these 2 lines! -->
    <!--[if lt IE 9]><script src="<?php //echo base_url('js/ie8-responsive-file-warning.js')?>"></script><![endif]-->
    <script src="<?php echo base_url('assets/js/ie-emulation-modes-warning.js')?>"></script>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

    <!-- Custom styles for this template -->
    <link href="<?php echo base_url('assets/css/carousel.css')?>" rel="stylesheet">
    <link href="<?php echo base_url('assets/css/frac_reset.css')?>" rel="stylesheet">
    <link href="<?php echo base_url('assets/css/frac_style.css')?>" rel="stylesheet">
    <link href="<?php echo base_url('assets/css/fractionslider.css')?>" rel="stylesheet">
    <link href="<?php echo base_url('assets/css/app.css')?>" rel="stylesheet">
  </head>
<!-- NAVBAR
================================================== -->
  <body>
    <div class="navbar-wrapper">
      <div class="header-container">

        <nav class="navbar navbar-inverse navbar-static-top" role="navigation">
          <div class="container">
						<img src="<?php echo base_url('assets/images/logomio.png')?>" alt="1Stop-HomeShop" />
              <ul class="nav navbar-nav pull-right">
                <li class="active"><a href="#">Home</a></li>
                <li class="dropdown">
									<a href="#" class="dropdown-toggle" data-toggle="dropdown">Furniture <span class="caret"></span></a>
                  <ul class="dropdown-menu" role="menu">
                    <li><a href="#">Action</a></li>
                    <li><a href="#">Another action</a></li>
                    <li><a href="#">Something else here</a></li>
                  </ul>
								</li>
                <li class="dropdown">
									<a href="#" class="dropdown-toggle" data-toggle="dropdown">Kitchen Ware <span class="caret"></span></a>
                  <ul class="dropdown-menu" role="menu">
                    <li><a href="#">Action</a></li>
                    <li><a href="#">Another action</a></li>
                    <li><a href="#">Something else here</a></li>
                  </ul>
								</li>
                <li class="dropdown">
									<a href="#" class="dropdown-toggle" data-toggle="dropdown">Lightning <span class="caret"></span></a>
                  <ul class="dropdown-menu" role="menu">
                    <li><a href="#">Action</a></li>
                    <li><a href="#">Another action</a></li>
                    <li><a href="#">Something else here</a></li>
                  </ul>
								</li>
                <li class="dropdown">
									<a href="#" class="dropdown-toggle" data-toggle="dropdown">Textiles <span class="caret"></span></a>
                  <ul class="dropdown-menu" role="menu">
                    <li><a href="#">Action</a></li>
                    <li><a href="#">Another action</a></li>
                    <li><a href="#">Something else here</a></li>
                  </ul>
								</li>
                <li><a href="#contact">Contact</a></li>
              </ul>
						<!--{__NAV__}-->
          </div>
        </nav>

      </div>
    </div>
	<div class="slider-wrapper">
	</div>
<div class="container marketing">
	<div class="row">
		<div class="col-lg-12">

			<?php foreach ($categories as $categories_item): ?>

			<h2><?php echo $categories_item['category_id'] ?></h2>
			<div class="main">
				<?php echo $categories_item['category_name'] ?>
			</div>
			<p><a href="<?php echo 'categories/'.$categories_item['category_id'] ?>">View article</a></p>

			<?php endforeach ?>
	
		</div>
	</div>
</div>

    <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="<?php echo base_url('assets/js/bootstrap.min.js')?>"></script>
    <script src="<?php echo base_url('assets/js/docs.min.js')?>"></script>
    <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
    <script src="<?php echo base_url('assets/js/ie10-viewport-bug-workaround.js')?>"></script>
    <script src="<?php echo base_url('assets/js/jquery.fractionslider.min.js')?>"></script>
    <script src="<?php echo base_url('assets/js/fractionslider_init.js')?>"></script>
    <script src="<?php echo base_url('assets/js/knockout.js')?>"></script>
		<script type="text/javascript">
			var baseurl = "<?php print base_url(); ?>";
			$(document).ready(function()
			{
				var cat = [];
				$('#btn').on('click', function(){
					$.ajax( {
						type: 'post',
						url: baseurl+'listcat',
						dataType: 'json',
						success: function ( result ) 
						{
							cat = result;
						},
						error: function ( result )
						{
							alert(JSON.stringify(result, null, 4));
						}
					} );
				});
				$(function() {
					model = {
						categories: ko.observableArray(cat)
					};
					ko.applyBindings(model);
				});

			});
		</script>		
		
    <!--<script src="<?php //echo base_url('assets/js/test.js')?>"></script>-->
  </body>
</html>

Open in new window


Here the route.php
$route['default_controller'] = "welcome";
$route['404_override'] = '';

//$route['categories/(:any)'] = 'categories/view/$1';
$route['categories/listcat'] = 'Listcat';
$route['categories/view'] = 'categories/view/$1';
$route['categories'] = 'categories';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';

Open in new window


Actually the view for listcat procdesses data with php and Ajax seems unneeded, but this is only to check if I can access that page correctly - and I can. The Ajax call hould return an array which using knockout.js should fill the page with a formatted list. But we can leave knockout for the moment.
The problem is that Ajax return a 404 error and after 6 hours of tutorials, Google and manuals I'm going to be crazy!
Please, have you any idea?

Thanks in advance
ASKER CERTIFIED SOLUTION
Avatar of Rob
Rob
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Marco Gasi

ASKER

Hi, Rob. Take it easy. I've just now saw that I've finally another response. Now I'll go to try to process the result of the Ajax call in some way to be sure it's right, then I'll post here the result. But if want to feel good for the tomorrow celebration I suggest you to go to sleep, now :-)
I had done something wrong with routes: chaging them and changing tutorial I got a working Ajax call. I'll post here the link to my next question about CodeIgniter, Ajax and Knockout.js lol
Thank you! And Happy New Year!!!
Thanks Marco and glad you got it working!
Happy New year to you too
But Rob! What time is it now there?
8 am! So all ok :)
You don't need to sleep a lot, uh? If i sleep only 5 hours per night my head crashes! :-) Bye
It's called having a 3 years old and an infant. One wants a feed at 2am the other wants to get up at 7 am. *laughing* I just go along with it :)

I'll keep an eye it for your questions as I'm right into the mvc stuff at the moment
Oh, good times those times! Now the major is 15 years old and the other 13... and me 53!!! Happy New Year again, Rob.