php - Calling Controller method from javascript using CodeIgniter - Stack Overflow

I am using CodeIgniter ..I can't access the method from the controllerI have this script in my vie

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?

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?

Share Improve this question edited Mar 9, 2014 at 10:17 tereško 58.5k25 gold badges100 silver badges150 bronze badges asked Mar 9, 2014 at 8:54 KatherineKatherine 5734 gold badges17 silver badges43 bronze badges 9
  • What do you mean by can't access? Are there any errors in the debugger console? – Nope Commented Mar 9, 2014 at 8:55
  • can't access the method.. it says.. HTTP/1.1 404 Not Found .. and it points to my_base_url/ajax/ajaxSearch – Katherine Commented Mar 9, 2014 at 8:58
  • And of course you also tried "/ajax/ajaxSearch"? – dfsq Commented Mar 9, 2014 at 9:00
  • i tried it, and the url bees localhost/ajax/ajaxSearch – Katherine Commented Mar 9, 2014 at 9:03
  • 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 Commented Mar 9, 2014 at 9:21
 |  Show 4 more ments

3 Answers 3

Reset to default 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

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";
    }
}

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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745415225a4626717.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信