Question: I am trying to get the count of records and return the result number to my ajax success function to print it or get the value on the textbox.

the controller function is:

```
public function get_subaccount_count($id){ 
    $data = $this->accounts_model->get_count($id);
    echo json_encode($data);
}

```

and the model function:

```
public function get_count($id){
    $sql="SELECT COUNT(*) FROM $this->tablename";
    $this->db->where('node_parent',$id);
    return $this->db->count_all_results($this->tablename);  
}

```

and the javascript in the view is:

```
<script>
$('#sub_account').change(function(){
    var accountcode = document.getElementById("main_code").value;
    var subaccount = document.getElementById("sub_account").value;
    //-------- loop to get count of sub accounts and add sum +1 ------------
    $.ajax({
        type: 'GET',
        url: "<?php echo base_url();?>index.php/accounts/get_subaccount_count/"+$('#main_code').val(),
        data: {},
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            $('#account_code').empty();
            $.each(result.result, function(){ 
                $('#account_code').value = this[0];
            })
        }  
    });
    //-------- loop to get count of sub accounts and add sum +1 ------------
});
</script>

```

I want the `$('#account_code').value =`  to be populated by the count `result`.

Answer: 
Your controller only needs to call the model method and print the returned integer.

```
public function get_subaccount_count(int $id): void
{ 
    echo $this->accounts_model->get_count($id);
}

```

Your model doesn't benefit from the `$sql` declaration.

```
public function get_count(int $id): int
{
    return $this->db->where('node_parent',$id)->count_all_results($this->tablename);  
}

```

Your ajax block only needs to assign the printed value to the desired HTML element.

```
$.ajax({
    type: 'GET',
    url: "<?php echo base_url();?>index.php/accounts/get_subaccount_count/" + $('#main_code').val(),
    success: function (response) {
        $('#account_code').value = result;
    }
});

```

Or use `$.get` like this:

```
$.get("<?php echo base_url();?>index.php/accounts/get_subaccount_count/" + $('#main_code').val(), function(result) {
    $('#account_code').value = result;
});

```
Change like this:

```
$.ajax({
            type: 'GET',
            url: "<?php echo base_url();?>index.php/accounts/get_subaccount_count/"+$('#main_code').val(),
            data: {},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) {
              $('#account_code').empty();
              var counter = 0; // this line
              $.each(result.result, function(){ 
                counter++; //this line
                })}
              $('#account_code').value = counter; // and this line

        });

```