Using javascript function to load view

I am trying to load a view into my #teste div using this.id via JavaScript with no success. What's wrong with 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 the others)

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');

}

      

+3


source to share


2 answers


to avoid the "Failure ReferenceError: navbutton is not defined" error attach a click event function using 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 in HTML use



<li><a href="#" id="contato">Contato</a></li>

      

JSFIDLE test - in this example the ajax request will get a 404 error because the url is not defined correctly, but in your code should work.

TIP to make sure all the code is in the right place, look at the source code of the page after loading it into the browser (CTRL + U)

+1


source


Are you trying to load a string into an element? In this case, you need to pass the third argument TRUE when loading the 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 out the docs here .

0


source







All Articles