0

I am trying to display json_encode data from my back end controller to view using together with AJAX. The AJAX runs successfully and received the response that I needed. However, i am unable to display out on my HTML.

I have double-checked that there is certainly a response coming from the back end. Please do help me.

AJAX jQuery

$.ajax({
        type: 'post',
        url: 'index.php/Status/facility',
        dataType: "json",
        data: {id:id},
        success: function (response) {

            var len = response.length;

            console.log(len);

        for(var i=0; i<len; i++){
            var id = response[i].facility_id;
            var username = response[i].name;

            var tr_str = "<li class='pointer' id='" + (i+1) + "' onclick='changeClass(this.id)'><a>" + name +"</a></li>";

            $("#tabAjax").append(tr_str);
        }

          $('#exampleModalCenter').modal('show'); 

        }
  }); 

HTML

<ul class="nav nav-pills" id="tabAjax"></ul>

Controller

public function facility(){
    echo json_encode($data);
    //$this->load->view('templates/student/footer');
}

Response

{"facility_list":[{"facility_id":"1","name":"Table 1","facility_category":"1"}]}

2 Answers 2

1

I believe you need to access the data within facility_list so to do so firstly get a reference to that level of the response data and then iterate through it's child objects

var json=response.facility_list;

for( var n in json ){
    var obj=json[n];

    var id=obj.facility_id;
    var name=obj.name;
    var cat=obj.facility_category;

    var tr_str = "<li class='pointer' data-category='"+cat+"' id='" + (n+1) + "' onclick='changeClass(this.id)'><a>" + name +"</a></li>";

    $("#tabAjax").append( tr_str );
}
Sign up to request clarification or add additional context in comments.

1 Comment

oh great it work! Totally didn't know about the facility_list. Thanks!
0

The best way to implement this handle it at backend. You can prepared html at backend and send prepared html in response(in any key of array) and append according that. That will be more easy to handle response and no need to reload page every time.

$response = array(array('facility_id' => 1, 'facility_category' => 2, 'name' => 'abc'));
$returnResponse = array('status' => 'false', 'data' => '');
$str = '';
foreach ($response as $key => $resp) {
$str .= '<li class="pointer" data-category="' . $resp['facility_category'] . '" id="' . ($key+1) . '" onclick="changeClass(this.id)"><a> ' . $resp['name'] . ' </a></li>';
}
$returnResponse['status'] = true;
$returnResponse['data'] = $str;

Now in js file you can use:-

var html = response.data;

and append above html where you want.

Comments

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.