How to show json data in codeigniter [duplicate] How to show json data in codeigniter [duplicate] codeigniter codeigniter

How to show json data in codeigniter [duplicate]


function getDocCat(catId){     var currentValue = catId.value;      $.ajax({        type: "POST",        url: "<?php echo site_url('home/get_com_by_cat') ?>",        data: { data: currentValue },        dataType:'json',                     success: function(result){            // since the reponse of the sever is like this            // [            //     {"company_name":"Jalalabad Ragib-Rabeya Medical College"},            //     {"company_name":"Jalalabad Ragib-Rabeya Medical College"}            // ]            // then you can iterate on the array            // make sure you have a html element that            // has an id=load_company_name            var company = $("#load_company_name");            // here is a simpe way            $.each(result, function (i, me) {                // create a p tag                // insert it to the                 // html element with an id of load_company_name                var p = $('<p/>');                    // you can access the current iterate element                    // of the array                    // me = current iterated object                    // you can access its property using                    // me.company_name or me['company_name']                    p.html(me.company_name);                    company.append(p);            });        },        error: function() {            alert('Not OKay');        }    });}


$("load_company_name") will not return with a jQuery object.

The selector needs to be a className, id or some other valid CSS selector.This will stop your HTML insert from working as it has nothing to insert into.

Make sure your desired jQuery object is valid. Like, $('#load_company_name')


Once you selector is sorted, you must then make sure you can actually insert your JSON into your HTML. Use JSON.parse() to convert it into a JS object and then you can iterate over the object and insert it into the HTML.

Something like:

var resultObj = JSON.parse(result);for(item in resultObj) {  if(resultObj.hasOwnProperty(item)) {    $("#load_company_name").append('<span>' + item + '</span>');  }}// Or use jQueryvar $resultObj = jQuery.parseJSON(result);$resultObj.each(function() {  $("#load_company_name").append('<span>' + this.company_name + '</span>');});


Use json_decode in your controller. And don't forget the selectors of css and jquery.