Rlemm1991
Rlemm1991

Reputation: 505

Correct way for Codeigniter AJAX get data from MySQL database without refreshing

I am currently experimenting with AJAX and jQuery to complete some basic tasks without having to leave a webpage. My aim is to query a table on a database and append that information to a list without the page refreshing.

 <button class="button radius" id="btnList">Current Items</button>

This is my button which has the ID. ("trigger button");

my script looks like this

$('#btnList').click(function(e){
    $.ajax({
        url:"<?php echo base_url();?>/cashbook/get_item",
        datatype:'json',
        type:"POST",
        success: function(result){
            alert(result);
            $.each(result.results,function(item){
                $('ul').append('<li>' + item + '</li>')
            })
        }
    })
    $('#div_list').toggle(900)
})

My aim is when the button is clicked, it fires off and does its magic and returns the data and appends it to a list which when finished opens a Div which contains the list. The problem is I get an error "TypeError: undefined is not an object (evaluating 'a.length')" My controller

function get_item()

{
    $data = $this -> M_cashbook -> cashbook_items();

    echo json_encode($data);

}

Im not sure if what I'm doing in the controller is right but when its set to echo or print it returns the jSon string and flags up in the alert but also appears at the top of my screen as text, if changed to return json_encode the alert shows blank, no Json nothing works.

Am I doing the whole thing wrong?, and if, so what is the correct way of achieving what I would like to do.

Thanks

UPDATE:

function cashbook_items()
{
    $this -> db -> select('name');
    $this -> db -> from('items');
    $query = $this -> db ->get();

    return $query -> result();
}

This is my model

This is my 2 controller functions, the first is the default load of the page which calls the second one to get the content, the second one just doing the grunt work to call the database and return the data

function items()
{

    $data['items'] = $this ->get_item();
    $this->load->view('/holders/header');
    $this->load->view('/cash/v_cashbook_items_page',$data);
    $this->load->view('/holders/footer');
}

function get_item()

{
    $data = $this -> M_cashbook -> cashbook_items();

    echo json_encode($data);

}

Lastly the view

    <style>
    ul {
        list-style-type: none;
    }
</style>
<div align="center" style="padding-top: 1%" id="div_main">
    <div class="jumbotron">
        <h1>Cashbook Items</h1>

        <p>Add items to to cashbook so they used <br>when adding incomings and out goings later</p>

        <form id="items_form" data-abide>
            <div class="large-3 large-centered columns">
                <label>New Item Name
                    <input type="text" required name="item" id="item_name">
                </label>
                <small class="error">No item added</small>
            </div>

            <button class="button radius" id="btnItem">Submit</button>
        </form>
        <a href="#" data-reveal-id="firstModal" class="radius button" id="btnList">Item List</a>
    </div>

</div>

<div class="row">
    <div id="firstModal" class="reveal-modal" data-reveal align="center">
        <h3>Current Items</h3>

        <p>Reccuring Items in the database</p>
        <ul id="list_item">
        </ul>
    </div>
</div>
</div>
<br>

<script>

    $('#btnList').click(function (e) {
        $.ajax({
            url: "<?php echo base_url();?>/cashbook/get_item",
            dataType: 'text',
            type: "POST",
            success: function (result) {
                var obj = $.parseJSON(result);
                $.each(obj, function (index, object) {
                    $('#list_item').append('<li>' + object['name'] + '</li>');
                })
            }
        })
    })

    $('#items_form').submit(function (e) {
        e.preventDefault();
        var data = $('#item_name').val();
        alert(data);
        $.ajax({
            url: "<?php echo base_url();?>/cashbook/new_item",
            type: 'POST',
            data: "item=" + data,
            success: function () {
                alert('THIS WORKED');

            },
            error: function () {
                alert('Nah died');
            }

        });
    })
</script>

Upvotes: 4

Views: 21506

Answers (1)

Arzgethalm
Arzgethalm

Reputation: 516

you can use result_array(); if you are retrieving more than one row. it will return pure array.

function cashbook_items()
{
    $this -> db -> select('name');
    $this -> db -> from('items');
    $query = $this -> db ->get();

    return $query -> result_array();
}

then in your view:

$('#btnList').click(function(e){
    $.ajax({
        url:"<?php echo base_url();?>/cashbook/get_item",
        dataType:'text',
        type:"POST",
        success: function(result){
            var obj = $.parseJSON(result);
            console.log(obj);
           // $.each(result.results,function(item){
           //     $('ul').append('<li>' + item + '</li>')
           // })
        }
    })
    $('#div_list').toggle(900)
})

you can check what the obj returns using console.log(obj);

$.parseJSON(result); will result in the conversion of the encoded json to an array of object.

if you want to access the Parsed JSON, use the ff.

obj[0]

this indicates that you will return the first row of your query.

obj[0]['name'];

to access individual columns, you can use the name of that column. which you stated in your model.

$('#btnList').click(function(e){
    $.ajax({
        url:"<?php echo base_url();?>/cashbook/get_item",
        dataType:'text',
        type:"POST",
        success: function(result){
            var obj = $.parseJSON(result);
            $.each(obj,function(index,object){
                $('ul').append('<li>' +object['name']+ '</li>');
            })
        }
    })
    $('#div_list').toggle(900)
})

Edit:

In you View.

  <style>
    ul {
        list-style-type: none;
    }
</style>
<div align="center" style="padding-top: 1%" id="div_main">
    <div class="jumbotron">
        <h1>Cashbook Items</h1>

        <p>Add items to to cashbook so they used <br>when adding incomings and out goings later</p>

        <form id="items_form" data-abide>
            <div class="large-3 large-centered columns">
                <label>New Item Name
                    <input type="text" required name="item" id="item_name">
                </label>
                <small class="error">No item added</small>
            </div>

            <button class="button radius" id="btnItem">Submit</button>
        </form>
        <a href="#" data-reveal-id="firstModal" class="radius button" id="btnList">Item List</a>
    </div>

</div>

<div class="row">
    <div id="firstModal" class="reveal-modal" data-reveal align="center">
        <h3>Current Items</h3>

        <p>Reccuring Items in the database</p>
        <ul id="list_item">
        </ul>
    </div>
</div>
</div>
<br>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script> 
<!--dont forget to add your jquery if you are using jquery functions and methods! -->
<script>
$(document).ready(function(){ //remember to put document.ready function when you are using jquery then insert your jquery functions inside.
    $('#btnList').on('click',function (){
        $.ajax({
            url: "<?php echo base_url();?>index.php/cashbook/get_item",
            dataType: 'text',
            type: "POST",
            success: function (result) {
                var obj = $.parseJSON(result);
                $.each(obj,function(index, object) {
                    $('#list_item').append('<li>' + object['name'] + '</li>');
                });
            }
        })
    });


    $('#items_form').submit(function (e) {
        e.preventDefault();
        var yourItem = $('#item_name').val();
        $.ajax({
            url: "<?php echo base_url();?>/cashbook/new_item",
            type: 'POST',
            data: {data:yourItem},
            success: function (data) {
                alert('THIS WORKED');

            },
            error: function () {
                alert('Nah died');
            }

        })
    });

});
</script>

Your Controller:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class cashbook extends CI_Controller{
    function __construct() {
        parent::__construct();
            $this->load->helper('url');
            $this->load->database();
            $this->load->model('M_cashbook');
    }

    function index(){
        $this->load->view('load_your_view_here'); //load your view here if you are using index as your default action when loading the default controller.
    }

    function items(){
        $data['items'] = $this ->get_item();
        $this->load->view('/holders/header');
        $this->load->view('/cash/v_cashbook_items_page',$data);
        $this->load->view('/holders/footer');
    }

    function get_item(){
        $data = $this->input->post('data');
        $data = $this -> M_cashbook -> cashbook_items();
        echo json_encode($data);
    }
}

Upvotes: 5

Related Questions