lel
lel

Reputation: 327

PHP - JSON to HTML

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"}]}

Upvotes: 0

Views: 68

Answers (2)

SINGH
SINGH

Reputation: 397

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.

Upvotes: 0

Professor Abronsius
Professor Abronsius

Reputation: 33813

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

Upvotes: 1

Related Questions