Ajax call returns int instead of string in CodeIgniter

This is my model. get items will get the name of the item from the database according to location

class Itemsale_db extends CI_Model

    public function getItems($userid,$loc)
        {
            $sql = "SELECT DISTINCT Name from itransfile where";

            if (is_numeric($loc))
                $sql .= " location_id = ".$loc;
            else 
                $sql .= " location_id IN(SELECT location_id FROM client_locations where client_id = " .$userid. ")";

            $query = $this->db->query($sql);        
            $item = $query->result_array();
                return $item;
        }
}

This is my controller. getItemsAjax will call the model and return a json encoded array for viewing.

class ItemSale extends CI_Controller {

public function getItemsAjax($userid,$locid)
        {
            $this->load->model('itemsale_db');
             header('Content-Type: application/x-json; charset=utf-8');
             $item = $this->itemsale_db->getItems($userid,$locid);
             echo json_encode($item);
        }
}

Here is the javascript. loc is the location field, and elements is the element selection field

$(document).ready(function(){
        $('#loc').change(function(){ 
            $("#items > option").remove(); 
            var opt = $('<option />');
            opt.val('All');
            opt.text('All');
             $('#items').append(opt);
            var loc_id = $('#loc').val(); 
            var userid = "<?php echo $this->session->userdata('userid'); ?>";

            $.ajax({
                type: "POST",
                url: "<?php echo base_url()?>" + "index.php/itemsale/getItemsAjax/"+loc_id + "/"+userid, 

                success: function(item) 
                {
                $.each(item,function(Name) 
                {

                    var opt = $('<option />');
                    opt.val(Name);
                    opt.text(Name);
                    $('#items').append(opt); 
                });
                }

            });         

    });
 });

The Ajax call returns me a list of integers instead of the element name. enter image description hereenter image description here

console.log (item) enter image description here

+4
source share
1 answer

The problem with the code is the wrong $ function . each .

The first argument must be an index, and the second must be a value in the $ .each callback.

This is the correct $.eachcallback format.Function( Integer indexInArray, Object value )

ajax-:

$.each(item,function(index,Name) {//added index first and then value
    var opt = $('<option />');
    opt.val(Name);
    opt.text(Name);
    $('#items').append(opt); 
});

: , Name ad Index.

+1

All Articles