I am using CodeIgniter ..I can’t access the method from the controller
I have this script in my view
<script> function showHint(str){ if (str.length==0){ document.getElementById("txtHint").innerHTML=""; return; } var xmlhttp=new XMLHttpRequest(); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","ajax/ajaxSearch",true); xmlhttp.send(); } </script>
and i have a controller named ajax with a method ajaxSearch()
public function ajaxSearch(){ echo "received"; }
Folder Structure
htdocs/ AjaxTry/ AjaxSearchingMVC/ application/ controller/ ajax.php //controller ajaxSearch() //method views/ view_ajax.php // here is where the script is written
What could be the possible problem here?
Advertisement
Answer
Do the following…
In controller
create example.php
and leave ajax.php
like it is. And in views leave like you have already view_ajax.php
We are going to load data from example.php
with Ajax
Your ajax.php
should look like this
class ajax extends CI_Controller { public function index() { $this->load->helper('url'); // if you are going to use helpher don't forget to load it ( of course if you are not loading it by default ) $this->load->view('view_ajax.php'); // in `view_ajax.php` you must have JavaScript code } }
JavaScript code for testing purpose write like
<script> var xmlhttp=new XMLHttpRequest(); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ alert(xmlhttp.responseText); console.log(xmlhttp.responseText);// you will see OKKK in console } } xmlhttp.open("GET","../index.php/example",true); // first try `../index.php/example` ( extension depends if you enable/disable url rewrite in apache.conf ) , if this won't work then try base_url/index.php/example ( where you can specify base_url by static or with CodeIgniter helpher function ) xmlhttp.send(); </script>
Nest Step
example.php should look like this
class example extends CI_Controller { public function index() { echo "OKKK"; } }