Welcome Guest, Not a member yet? Register   Sign In
Ajax Controller
#1

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
Reply
#2

(This post was last modified: 07-09-2015, 07:43 AM by ivantcholakov.)

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.
Reply
#3

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

It is not my idea, I took it from another project. https://github.com/pyrocms/pyrocms/blob/...er.php#L84
Reply
#5

(This post was last modified: 07-09-2015, 02:43 PM by orionstar.)

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




Theme © iAndrew 2016 - Forum software by © MyBB