简体   繁体   中英

Ajax call returning int instead of string in CodeIgniter

This is my model. get items will get the item name 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 the json encoded array to view.

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 selection box and items is the item selection box

$(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); 
                });
                }

            });         

    });
 });

Ajax call returning me list of integers instead of items name. 在此处输入图片说明在此处输入图片说明

console.log(item) 在此处输入图片说明

Your code issue is this(Format of $.each function is incorrect).

First argument should be index and second should be value in $.each callback.

This is correct format of $.each callback Function( Integer indexInArray, Object value )

Use following code in ajax success:

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

Note: While you are using only single parameter in each callback its treating Name ad Index .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM