0

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?

tereško
  • 58,060
  • 25
  • 98
  • 150
Katherine
  • 573
  • 4
  • 17
  • 43
  • What do you mean by `can't access`? Are there any errors in the debugger console? – Nope Mar 09 '14 at 08:55
  • can't access the method.. it says.. HTTP/1.1 404 Not Found .. and it points to my_base_url/ajax/ajaxSearch – Katherine Mar 09 '14 at 08:58
  • And of course you also tried `"/ajax/ajaxSearch"`? – dfsq Mar 09 '14 at 09:00
  • i tried it, and the url becomes http://localhost/ajax/ajaxSearch – Katherine Mar 09 '14 at 09:03
  • @Katherine would you mind sharing the folder structure? – Kamran Ahmed Mar 09 '14 at 09:03
  • @Katherine please check my answer, if it works for you! – Kamran Ahmed Mar 09 '14 at 09:17
  • 2
    @Katherine: I don't know how you do it in PhP but in ASP.NET MVC we send the target url from the server down to the client within a data attribute or similar as the server always has the full URL available no matter which server/domain it is published to. In ASP/NET MVC we have server side C# helpers like `URL.Action('action', 'controller')` which returns the full and correct URL. I do not know what the equivelant is in PhP though. – Nope Mar 09 '14 at 09:21
  • @Katherine: Have a look at this SO post it mentions a few solution to obtain the full URL using codeigniter: [**http://stackoverflow.com/questions/2062086/how-to-get-controller-action-url-informations-with-codeigniter**](http://stackoverflow.com/questions/2062086/how-to-get-controller-action-url-informations-with-codeigniter) i.e: `$this->uri->segment(n);` and `$this->router->fetch_class();$this->router->fetch_method();` I don't know PhP so not sure if that helps or makes sense :) – Nope Mar 09 '14 at 09:25
  • @FrançoisWahl I guess it is the base_url() in PHP.. from the console i could say that the ajax url is correct – Katherine Mar 09 '14 at 09:25

3 Answers3

3

What I have been using in my project for ajax request is forming the Ajax URL like the following:

  1. Inside your view put a global variable, inside the head, with the value set to base_url() like so:

    var base_url = <?php echo base_url(); ?>
    
  2. Now inside your script, call this controller action, that you are trying to access, using the base_url like so:

    xmlhttp.open("GET", base_url + "ajax/ajaxSearch",true);
    

This would create your ajax URL like http://yourbaseurl/ajax/ajaxSearch and hopefully solve the problem for you!

NOTE

Your base_url must be something like http://localhost/yourprojectfolder/ for this to work

Kamran Ahmed
  • 11,809
  • 23
  • 69
  • 101
1

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";
    }
}
nanobash
  • 5,419
  • 7
  • 38
  • 56
  • What do you mean applicable, it doesn't matter. For testing purposes I'd suggest you to create some `example.php` (or whatever your server side scripting language is) and post something in it and specify this `example.php` path into JavaScript and see the result – nanobash Mar 09 '14 at 09:08
  • this code comes from that format and it works, but i tired to change it to mvc style, and now it has a problem – Katherine Mar 09 '14 at 09:12
  • @Katherine You know, from your structure I can't even see where is `ajax/ajaxSearch` – nanobash Mar 09 '14 at 09:13
  • @Katherine In which file do you have `php` script from your structure ? and in which file is written your `JavaScript` ? – nanobash Mar 09 '14 at 09:14
  • i updated the folder structure.. javascript is written in view_ajax, ajaxSearch method is in ajax controller – Katherine Mar 09 '14 at 09:17
  • i'm not the one who down voted your answer.. I actually appreciate people who tries to help me – Katherine Mar 09 '14 at 09:19
  • @Katherine Specify `ajax.php` in JavaScript, and I'd suggest you to comment whole your `ajax.php` file and simple `echo "something"` , and see the result – nanobash Mar 09 '14 at 09:23
  • @Katherine Have you tried like so `ajax.php/ajaxSearch` ? – nanobash Mar 09 '14 at 09:33
  • @crypticous No offense, but it seems like you don't have any experience with Codeigniter! – Kamran Ahmed Mar 09 '14 at 09:35
  • @crypticous i tried it, it outputted an html file i guess... with a title of XAMPP for Mac OS X 1.7.3 – Katherine Mar 09 '14 at 11:06
  • @Katherine Did you try with both of them (with base_url and with `../index.php/example` ? – nanobash Mar 09 '14 at 11:08
  • @Katherine I've tested what I posted and it is working just fine, I think you are missing something – nanobash Mar 09 '14 at 11:08
  • @crypticous now i tried it with the base_url included in the link, then i capitalized the "example" name for the controller.. it works, thank you – Katherine Mar 09 '14 at 11:32
  • @crypticous but if i remove the index.php in the url, then it will not work, given that i already set to remove the index.php in htaccess – Katherine Mar 09 '14 at 11:36
  • @Katherine `index.php` in CodeIgniter app is a bridge between `controller` and `views`, so it necessary during `Ajax` call nonetheless that in `apache.conf` you may have `DirectoryIndex` `index.php` – nanobash Mar 09 '14 at 11:42
0

Add the following function in the JS script

function FetchData() {
    var valueFromClient = document.getElementById("ReplaceWithID").value;

alert("Received from client:"+valueFromClient );

    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for modern browsers
        xmlhttp = new XMLHttpRequest();
    } else {
        // code for old IE browsers
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            alert("Received from server:"+this.responseText);
        }
    };

    xmlhttp.open("POST", "http://localhost:52322/ControllerName/MethodName?CurrentC=" + valueFromClient , true);
    xmlhttp.send();
}
  1. Change the Port : 52322 according to your port number.
  2. Its a localhost. So you may have to change it once your site goes online.
  3. on the View. Add onChange(FetchData())

For Example:

<select id="AnyIDHERE" onchange="updateProvince()"> </select>
Pradip Tilala
  • 1,715
  • 16
  • 24
Saim
  • 73
  • 1
  • 4