0

I am using codeigniter's MVC and I am trying to use Ajax to load a function from my controller file.

My Ajax code loads the php file perfectly without the codeigniter MVC. But in codeigniter I am unsure how to call the php file/function inside the Ajax function.

My code looks like this without codeigniter and it works fine

<script>
function showUser(str) {
if (str == "") {
    document.getElementById("txtHint").innerHTML = "";
    return;
} else { 
    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 (this.readyState == 4 && this.status == 200) {
            document.getElementById("txtHint").innerHTML = this.responseText;
        }
    };
       ////////////////////////////////////////////
      //////// This loads find without MVC////////
     ////////////////////////////////////////////
    xmlhttp.open("GET","ajax-php.php?q="+str,true);
    xmlhttp.send();
    ////////////////////////////////////////////
   //////// This loads find without MVC////////   
  ////////////////////////////////////////////
}
}
</script>

But it doesnt work in codeigniter's view file as shown below

    <script>
    function showUser(str) {
        if (str == "") {
            document.getElementById("txtHint").innerHTML = "";
            return;
        } else { 
            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 (this.readyState == 4 && this.status == 200) {
                    document.getElementById("txtHint").innerHTML = this.responseText;
                }
            };
              ////////////////////////////////////////////
             //////// this is problem////////////////////
            ////////////////////////////////////////////
            xmlhttp.open("GET","<?= base_url(); ?>" + "/controller_page/ajax_file.php?q="+str,true);
            xmlhttp.send();
           ////////////////////////////////////////////
          //////// this is problem////////////////////
         ////////////////////////////////////////////
        }
    }
 </script>

So the problem is in the code below,( which has been cut out from the above code to make it easier to read) as I am not sure how to load the function inside the script in an MVC envirosment for codeigniter

              ////////////////////////////////////////////
             //////// this is problem////////////////////
            ////////////////////////////////////////////
            xmlhttp.open("GET","<?= base_url(); ?>" + "/controller_page/ajax_file.php?q="+str,true);
            xmlhttp.send();
           ////////////////////////////////////////////
          //////// this is problem////////////////////
         ////////////////////////////////////////////

Thanks in advance

2 Answers 2

2

Your path should be:

xmlhttp.open("GET","<?= base_url(); ?>" + "/controller_name/controller_function_name?q="+str,true);
xmlhttp.send();

Lets assume controller_name= user and controller_function_name = my_test_ajax. Then controller user should look like as follows:

class User extends CI_Controller {
     public function __construct(){
        parent::__construct();
        // load model helper etc 
     }

     public function my_test_ajax(){
        // get q
        $qry= $_GET['q'];
        echo $qry;
     }
}

Hope it should help you.

Sign up to request clarification or add additional context in comments.

1 Comment

Apologies for not responding earlier, I didnt see it
0
<?= base_url(); ?>

This is going to obligate you to smash JS together with PHP. In the long run you will lose time and sanity because of it. What you should do is create JS config values with a view file:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
<script type="text/javascript">
    var CONFIG = {
                'base_url': '<?php echo base_url(); ?>',
                'language': '<?php echo $this->config->item('language'); ?>',
                'permitted_uri_chars': '<?php echo $this->config->item('permitted_uri_chars'); ?>',
                'cookie_prefix': '<?php echo $this->config->item('cookie_prefix'); ?>',
                'cookie_domain': '<?php echo $this->config->item('cookie_domain'); ?>',
                'cookie_path': '<?php echo $this->config->item('cookie_path'); ?>',
                'csrf_expire': '<?php echo $this->config->item('csrf_expire'); ?>',
                'csrf_token_name' : "<?php echo $this->security->get_csrf_token_name(); ?>",
                'csrf_cookie_name' : "<?php echo $this->security->get_csrf_hash(); ?>",
                'picture_max_upload_size' : "<?php echo Settings_model::$db_config['picture_max_upload_size']; ?>"
            }
</script>

As you can see you can "transport" any PHP value to JS by loading this view file in your template e.g.:

<?php $this->load->view('generic/js_system'); ?>

In the HTML template I add this right before my app.js file which holds the actual AJAX connection methods.

Now you can just call your base url like:

<script>
$.ajax({
   method: 'POST',
   url: CONFIG.base_url + 'module/controller/method/',
   dataType: 'json',
   data: $data
}).done(function(result) {
   // etc...
}
</script>

Good luck.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.