Tuesday 28 August 2012

Json and Ajax in Codeigniter


Json & Ajax

In view we have to put like this..

If you selecting the dropdown the request will be sent to ajax and response data will be json ...





<script type="text/javascript">
function showUser(str)
{

if (str=="")
  {

  document.getElementById("txtHint").innerHTML="";
  return;
  }

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)
    {
 //alert('hai');
 //alert(xmlhttp.responseText);
      //document.getElementById("objId").innerHTML=xmlhttp.responseText;
      putdata(xmlhttp.responseText);
 
    }
  }
 
xmlhttp.open("GET","page/ajax/"+str,true);
xmlhttp.send();
}
function putdata(ajaxobject){
var res=JSON.parse(ajaxobject);
//alert(res.data[0].id);
//alert(res);
//

//alert(arr[6]);
//alert(arr);
document.getElementById('purl').value=res.data[0].url;
document.getElementById('ptitle').value=res.data[0].title;
document.getElementById('pmetades').value=res.data[0].meta_des;
document.getElementById('pmetakey').value=res.data[0].meta_key;
//document.getElementById('pcontent').value=res.data[0].content;
CKEDITOR.instances.pcontent.setData(res.data[0].content);
//document.getElementById('emailTemp').value=arr[4];

//alert(arr[6]);
}

</script>







 <select id="type" onchange="showUser(this.value);" name="type">
              <option >Please select one</option>
                <option value="1">Our Partner</option>
                <option value="2">Welcome</option>
                <option value="3">Coversage </option>
              </select>




Controller:


function ajax(){
  $this -> db -> select('*');
$this -> db -> from('page');
$this -> db -> where('page_id', $this->uri->segment(3));
$query = $this->db->get();
$JSON1=array('operation'=>'1','status'=>'ok','msg'=>'msg','data'=>$query->result());
echo json_encode($JSON1);
//echo "data:".json_encode();

}




No comments:

Post a Comment