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');
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With