4

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>
4
  • is that not what I'm doing with the URL? /cashbook/get_item cashbook the controller and get_item the function within the cashbook? Commented Mar 27, 2015 at 14:13
  • can you show us your model? Commented Mar 27, 2015 at 14:15
  • datatype:'json' should be dataType:'json'. Note the capital 'T'. Commented Mar 27, 2015 at 16:33
  • deleted my comment. Misread the code Commented Mar 27, 2015 at 20:25

1 Answer 1

5

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);
    }
}
Sign up to request clarification or add additional context in comments.

11 Comments

Thanks for the idea, when using your code example with echo/print in my controller the text is still on the top of the page but the console.log shows multiple objects which when clicked displays the each row. however the a.legnth error appears . When changing back to return in the controller i get an error [Error] SyntaxError: JSON Parse error: Unexpected EOF parse (jquery.js, line 25) parseJSON (jquery.js, line 25) success (items, line 87) k (jquery.js, line 24) fireWith (jquery.js, line 24) c (jquery.js, line 25) (anonymous function) (jquery.js, line 26) on click
thanks this did help display the data but now I'm having an issue of the son object being pinned to the top of the page because of the echo/print, if i change to a return i get no son object
@Riemm1991 use this format in your controller when you pass the data to view: echo json_encode($data);
hi thanks again for replying, I'm already doing this and it does return the jSON and it is usable but the object it self is being echoed above my header as if i were debuging it with print_r, this is if i echo or print it
@Riemm1991 It is possible that some function in your controller echoes the object, kindly double check it. or post your whole controller here so that we can see. thank you.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.