Solved

CodeIgniter and Ajax calls for a dummy

Posted on 2014-12-30
10
288 Views
Last Modified: 2014-12-31
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
0
Comment
Question by:Marco Gasi
  • 6
  • 4
10 Comments
 
LVL 42

Accepted Solution

by:
Rob Jurd, EE MVE earned 500 total points
Comment Utility
I'll take an in depth look soon, however you should start by making sure there is a function for every View in the controller, even if they do not do anything.

Then look at the routes to making sure they're operating ok. Test each route in the browser by navigating directly to each one.
0
 
LVL 30

Author Comment

by:Marco Gasi
Comment Utility
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 :-)
0
 
LVL 30

Author Closing Comment

by:Marco Gasi
Comment Utility
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!!!
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
Comment Utility
Thanks Marco and glad you got it working!
Happy New year to you too
0
 
LVL 30

Author Comment

by:Marco Gasi
Comment Utility
But Rob! What time is it now there?
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
Comment Utility
8 am! So all ok :)
0
 
LVL 30

Author Comment

by:Marco Gasi
Comment Utility
You don't need to sleep a lot, uh? If i sleep only 5 hours per night my head crashes! :-) Bye
0
 
LVL 42

Expert Comment

by:Rob Jurd, EE MVE
Comment Utility
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
0
 
LVL 30

Author Comment

by:Marco Gasi
Comment Utility
Oh, good times those times! Now the major is 15 years old and the other 13... and me 53!!! Happy New Year again, Rob.
0
 
LVL 30

Author Comment

by:Marco Gasi
Comment Utility
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
spacing 5 24
Editing login page in zencart. 2 13
Phone Dialer 5 35
google sheets, auto insert date into cell when data is moved 11 39
Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now