Reputation: 79
I trying to load a view into my div #teste with this.id through JavaScript without success. What's wrong on my function?
JavaScript function below
<script type="text/javascript">
var baseurl = '<?php site_url(); ?>'; //raiz do website
function navbutton(id) {
$.ajax({
type: 'GET',
url: baseurl+'main/'+id,
dataType: 'html',
success: function(html) {
$('#teste').html(html);
}
});
}
HTML button
<li><a href="javascript:void(0)" id="contato" onclick="navbutton(this.id)">Contato</a></li>
My main Controller (one function to call all others views)
class Main extends CI_Controller {
var $_data = array();
public function index()
{
if (!$this->uri->segment(1) && !$this->uri->segment(2)) {
$view = 'inicio';
}
if ($this->uri->segment(1) && !$this->uri->segment(2)) {
$view = $this->uri->segment(1, 'inicio');
}
if ($this->uri->segment(1) && $this->uri->segment(2)) {
$view = $this->uri->segment(1, 'inicio') . '/' . $this->uri->segment(2, '');
}
if (!file_exists(APPPATH . 'views/' . $view . EXT)) {
$view = "404";
header("HTTP/1.0 404 Not Found");
}
$this->load->view('templates/header');
$this->load->view($view, $this->_data);
$this->load->view('templates/footer');
}
Upvotes: 3
Views: 3377
Reputation: 2073
to avoid to get 'Uncaught ReferenceError: navbutton is not defined' error attach on click event function with javascript:
var baseurl = '<?php site_url(); ?>'; //raiz do website
function navbutton(id) {
$.ajax({
type: 'GET',
url: baseurl+'main/'+id,
dataType: 'html',
success: function(html) {
$('#teste').html(html);
},
error:function(v1,v2,v3){
alert('Something went wrong'); }
});
}
$("#contato").on('click',function(event){
event.preventDefault();
navbutton(this.id);
});
And on HTML use
<li><a href="#" id="contato">Contato</a></li>
JSFIDLE test - in this example the ajax request will get error 404 because the url is not defined proper but in you code must work.
HINT to make sure all code is in the proper place, take a look in the source code of page after is loaded in browser (CTRL+U)
Upvotes: 1
Reputation: 7111
Are you trying to load string to element? In that case you need to pass third argument TRUE when loading view method.
$view = $this->load->view('templates/header', '', TRUE);
$view .= $this->load->view($view, $this->_data, TRUE);
$view .= $this->load->view('templates/footer', '', TRUE);
echo $view;
Check in docs here.
Upvotes: 0