Solved

CodeIgniter and Ajax calls for a dummy

Posted on 2014-12-30
10
335 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 4
10 Comments
 
LVL 43

Accepted Solution

by:
Rob earned 500 total points
ID: 40523914
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 31

Author Comment

by:Marco Gasi
ID: 40523923
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 31

Author Closing Comment

by:Marco Gasi
ID: 40524368
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
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
LVL 43

Expert Comment

by:Rob
ID: 40524468
Thanks Marco and glad you got it working!
Happy New year to you too
0
 
LVL 31

Author Comment

by:Marco Gasi
ID: 40524474
But Rob! What time is it now there?
0
 
LVL 43

Expert Comment

by:Rob
ID: 40524489
8 am! So all ok :)
0
 
LVL 31

Author Comment

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

Expert Comment

by:Rob
ID: 40524510
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 31

Author Comment

by:Marco Gasi
ID: 40524729
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 31

Author Comment

by:Marco Gasi
ID: 40525110
0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
javascript duplicates 9 26
Check for Numeric Phone Field 14 48
Drag & Drop Error 5 32
how to properly reinitialize tinyMCE rich text html editor 8 17
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
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 the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

751 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