Search code examples
codeigniter-4

Adding external javascript in views codeigniter4 not the assets uses base_url()


I'm using codeigniter 4. I have been doing ajax request directly to a view file. Now I want to use external ajax_file_name.js and call it inside that view

My Views directory looks like this:

--| Views
-----| Products
---------| index.php
---------| ajaxFolder
--------------|ajax_operation.js

I always do ajax in index like this

Views/ Products/ index.php

$(function($){
    
    //my ajax cruds functions goes here

})(jQuery);

But now I want to be able to use ajax external file like this:

Views/ Products/ index.php

<script src="/ajaxFolder/ajax_operation.js"></script>

Controllers/Product.php

public function index()
{
    return view("Products/index");
} 

How can I achieve that since controller load php file?

Thanks.


Solution

  • In this case you will need to move your js files to CodeIgniters public folder. This way, when you access the file from the web server, the path you have shown will be inside the correct folder. As you may know, the public folder is the default "web root folder" for CI4.

    --| app
    -----| Views
    --------| Products
    ------------| index.php
    --| public
    -----| ajaxFolder
    ----------| ajax_operation.js
    

    With this structure, the script tag you have shown in your view will path correctly in the browser.

    <script src="/ajaxFolder/ajax_operation.js"></script>

    For reference, this is the CI4 docs on the folder structure.