CodeIgniter Forums
Ajax Controller - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Model-View-Controller (https://forum.codeigniter.com/forumdisplay.php?fid=10)
+--- Thread: Ajax Controller (/showthread.php?tid=62392)



Ajax Controller - maxime59 - 07-09-2015

Hi at all,

I'm new with CI but not very with MVC models so I wanted to have a dedicated Controller called Ajax to handle all Ajax requests as I did in a homemade framework.

When I want to use Ajax I'm already in a Controller and the request gives a 404 to http://xxxx/currentcontroller/ajax/mymethod.
I can understand that the current controller is in the URI because of relative path.

I have found on the web that people usually write Ajax requests in a view in order to have the base_url() or site_url() available to build correctly the URI, but in my case, I want my Ajax requests in a javascript file.

Is there a solution to reach http://xxxx/ajax/mymethod without writing the js code in a view or writing absolute paths in Ajax URL parameter ?

Cheers

Max


RE: Ajax Controller - ivantcholakov - 07-09-2015

At the beginning ot the head section of your HTML template you may place the following JavaScript:

Code:
<script type="text/javascript">
    //<![CDATA[
        var site_url = '<?php echo site_url(); ?>';
        // ... and so forth.
    //]]>
    </script>

The variable site_url will be available to the other JavaScripts within the page then, including your AJAX calls.


RE: Ajax Controller - maxime59 - 07-09-2015

Thanks a lot ivantcholakov.
The idea is simple but terribly efficient !


RE: Ajax Controller - ivantcholakov - 07-09-2015

It is not my idea, I took it from another project. https://github.com/pyrocms/pyrocms/blob/2.1/master/system/cms/core/Public_Controller.php#L84


RE: Ajax Controller - orionstar - 07-09-2015

I am using pure JS for this without inline code:
Code:
window.SITE_URL = window.location.protocol + "//" + window.location.host + "/";