I’ve create a codeigniter app that includes a page with some ajax.
I’m trying to prove to myself that the ajax page is in fact working. That is, that only one section of my page is being updated, and the rest stays as is.
Here’s my code in the controller:
(index is the method that is called on initial page load. index2() is called when the refresh button is clicked)
public function index()
{
$this->load->model('locations_model');
$data['clienthistory'] = $this->locations_model->get_locations();
$data['main_content'] = 'dashboard';
$this->load->view('includes/template', $data);
}
public function index2()
{
$this->load->model('locations_model');
$data['clienthistory'] = $this->locations_model->get_locations();
return json_encode($data['clienthistory']);
}
And here is my view:
<h2>timer test</h2>
<?php echo now();?>
<h2>Latest Client Status</h2>
<?php echo form_open('Dashboard/index');
echo form_submit('submit', 'Refresh Client Data', 'id="clientsubmit" class="btn-primary"');
?>
<div class="row-fluid">
<div class="span12" id="ajaxcontainer">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>IP</th>
<th>Name</th>
<th>Last Updated</th>
</tr>
</thead>
<tbody>
<?php foreach ($clienthistory as $histitem): ?>
<tr>
<td><?php echo $histitem['network'] ?></td>
<td><?php echo $histitem['name'] ?></td>
<td><?php echo $histitem['lastupdated'] ?></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</div>
<?php echo form_close(); ?>
<script type="text/javascript">
$('#clientsubmit').click(function() {
$.ajax({
url:"<?php echo site_url('Dashboard/index2'); ?>",
type: 'POST',
dataType: 'html'
success: function(returnDataFromController) {
$('#ajaxcontainer').html(returnDataFromController)
}
});
return false;
});
</script>
The idea is to display the current time on the page, in an area that is not supposed to be updated by my ajax call. But when I click on my refresh button, in addition to updating the table data, the time is being updated too.
I’m not sure I understand why this is happening. any help would be appreciated. apologize in advance for the remedial questions – just new to codeigniter and to ajax.
thanks.
Your button is a
submitso it will refresh the page when clicked.You need to change it to something else, like
<a></a>and append a action to it, something like this:Since you are using twitter bootstrap, the link won’t mess with your layout adding a
btnto it’s class.Without the
submitbutton, your page won’t be refreshed and your date function will be intact.And just for precaution, disable that link/button when clicked until the request is returned.
And on your ajax call you will just update the
ajaxcontainerelement.Hope it helps.