Reputation: 1828
How does codeigniter MVC work with AJAX?
More specifically, what is the most basic AJAX functionality that allows one to send data to a model, then back to a view? Could you explain the majority of the components involved in depth?
Upvotes: 1
Views: 1125
Reputation: 1828
As a newbie to PHP/JS/Codeigniter and web development in general, understanding the concepts behind AJAX and how it connects with codeigniter was one of the more confusing things to wrap my head around.
The majority of answers on SO and other tutorial sites seemed to come from the viewpoint of someone very experienced, where it didn't make much sense to the laymen.
As such, I've decided to do a very 'basic' answer that should hopefully help most newcomers who are trying to understand how and why this code works. Keep in mind, that this is supposed to be a very basic explanation. Feel free to edit, but try to keep it simple and without jargon.
I'm not going to get into the details regarding definitions, as you can do that through google. I'll start with the first step, the javascript.
On your page, you'll want to find a spot for the actual AJAX. Be sure to have JQUERY loaded. for more information on that, Google 'Jquery', and load the library ASAP.
For this scenario, we'll add our script directly into the HTML, because its easier. Alternatively, you could load an external JS script similarly to how you load stylesheets.
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<meta property="og:image" content="<?php echo base_url()?>img/logo/logo-big.jpg"/>
<!--[if lt IE 10]>You are living in the past...Upgrade you Browser!! OMFG (google chrome/fire fox)<![endif]-->
<html lang="en">
<head>
<script src="/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="1.8.21/jquery-ui.min.js"></script>
<link href="<?php echo base_url()?>css/account.css" rel="stylesheet" type="text/css"
</head>
<body>
<div class="ajaxContainer">
<form id="ajaxForm" method="get">
<input type="text" id="ajax_input" name="q" placeholder="Type Here"/>
<input type="submit" id="ajax_submit" value="" />
</form>
</div>
</body>
Inside the HTML, add the following script (anywhere, though I usually add it at the top):
<script>
$('.ajaxContainer').delegate('#ajaxForm', 'submit', function() {
$.ajax({
var submitdata = $('#ajax_input').val();
type: "POST",
url: '/ajax/getdata',
dataType: 'json',
data: { submitdata: submitdata },
success: function(data){
$('#ajax').html(data['content']);
}
});
return false;
});
</script>
As for the explanation:
1 $('.ajaxContainer').delegate('#ajaxForm', 'submit', function() {
I used jqueries delegate
function to pick up the submit click. Simple enough. It scans all ids/classes within the specified div/class (.ajaxContainer
).
2 $.ajax({
This is where the magic starts.
3 var submitdata = $('#ajax_input').val();
Here you will simply 'grab' the data that you want to use in your controller/model. This isn't necessary, but it certainly helps for this explanation. Here, we are taking the value inside #ajax_input
and adding it to the javascript variable submitdata
for use later on.
4 type: "POST",
Hopefully you are familiar with post/get and typical html form submission. In this example, we specify POST for how we will submit the data. You can change to GET if you want to. Play around with it.
Notice how each section is separated by a ,
Not overly complicated, just something to take note of. In fact, there are many other things you can add to this code. Take a look at jquery AJAX documentation for more info and play around. http://api.jquery.com/jQuery.ajax/
5 url: '/ajax/getdata,
This is the controller you are calling. I'll explain more later, however, you want to create and ajax
controller and a function inside it named getdata
. Again, youre simply pointing ajax to a URL. In theory, you could access the page manually by typing it in the address bar. Once you pass the data to that controller, you are working with PHP/codeigniter, and one step closer to successfully performing an AJAX call.
6
dataType: 'json',
data: { submitdata: submitdata },
Specify what type of data you expect to be returned with dataType
.
data:
sends POSTED data to your controller to be picked up and used in your model. the first submitdata:
is the variable we made earlier, and the second represents the name you will be searching for in your controller.
At this point, we will move over to the controller. If you recall, we directed our AJAX call to the url:
- /ajax/getdata,
I alluded to creating a controller/function that mirrored that URL. Heres what it would look like:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Ajax extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('logic_model');
}
public function getdata()
{
//First, grab the data being passed via AJAX through post
$submitteddata = $this->input->post('submitdata');
//Then send that data to your model to do whatever you want.
$data['content'] = $this->logic_model->dosomething($submitteddata);
// you need to echo the data. json_encode turns an array into a JSON formatted string. Without this, you will not receive a success, and you lose sir, goodday.
echo json_encode($data);
}
}
And our Model, aka: logic_model
->
public function dosomething(submitteddata) { return "Success!" }
It returns Success!
without will feed back into the controller, $data['content']
and then will be echoed.
We now return to javascript where it checks everything that happened and performs either the success:
or failure:
function (read documentation for more on failure).
7
success: function(data){
alert(data['content']);
}
As you can see, the function includes the parameter, data
This represents the JSON we echoed in the ajax controller. It works just like an array. If successful, it should alert the returned string 'Success!"
And its THAT simple. Obviously, as your task changes, so do a few of the steps, but it will typically just expand on the above scenario.
Hopefully people find this helpful coming from someone who isn't that adept at PHP/AJAX yet, but has come a long way.
Upvotes: 3