Friday 28 November 2014

Fetch data from database in codeigniter and convert in json.



Hey Morning fellas,

Hope you are doing well.

A quick tutorial for ajax request in codeignitor and fetching data from db in Json Format.

First we need to have the database with a "unique _id" which we will use for calling the row.


<script>                function fetchdata_4_edit(val)        {                      if (window.XMLHttpRequest)            {// code for IE7+, Firefox, Chrome, Opera, Safari            xmlhttp=new XMLHttpRequest();            }            else            {// code for IE6, IE5            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");            }            xmlhttp.onreadystatechange=function()            {            if (xmlhttp.readyState==4 && xmlhttp.status==200)                {                 //document.getElementById('group_info').style.display='none';                document.getElementById("response").innerHTML=xmlhttp.responseText;
                }            }            xmlhttp.open("GET","<?php echo base_url();?reception/fetchdata_4_edit?unique_id="+val,true);            xmlhttp.send();                                            }                                </script>

Here response is the div where we will check our json values.
Unique id is the row unique id for database.



As you can see my controller name is reception and method is fetchdata_4_edit.
so this is what we do.
        function fetchdata_4_edit()        {                        $uniq_id = $_GET['unique_id'];                                    $this->db->select('*');            $this->db->from('table_1');            $this->db->join('table_2', 'table_2.colomn_name = table_1.column_name');            $this->db->where('table_1.column_name', $uniq_id);
            $query = $this->db->get();                        foreach ($query->result() as $row)            {                print json_encode($row);            }            

               }


Thats its.Now when you use this js Function with onclick.you will see the response in Json Format like this.


{"id":"22","cust_id":"1","call_level":"1","extension":"0","action_type":"2","title":"Voice_Mail","default_sound":"","hold_sound":"","error_sound":"","vm_pre_sound":"sound1","vm_post_sound":"sound1","welcome_sound":"","no_input_sound":"","wrong_input_sound":"","call_mode":null,"dest_email":"er.shakun90@gmail.com","go_to_level":null,"use_who_call":null,"who_call_api":null,"fallback":null,"notification":null,"sortor":"2","addDate":"2014-11-28 12:48:47","updateDate":"0000-00-00 00:00:00","desc":"Vm_Desc","action_id":"74","time_slot_type":"0","slot_date":"2014-11-28","slot_day":"8","slot_time_from":"00:00:00","slot_time_to":"00:00:00"}


Thanks




3 comments: