2

I'm having trouble with using correct path names in local Javascript with a Codeigniter backend.

My Codeigniter file directory looks like this

-user_data
-application
-system
-assets

In my JS I define the path I want to use which is user_data like so:

var user_file_location = 'user_data';

I have a function (in my local JS) that preloads images based on a given url:

loader.addImage(image_url);

Now when I try to load an image from the directory user_data like so:

loader.addImage(user_file_location + 'grass.png') 

I get the following error in the browser console:

GET http://localhost/index.php/userdata/grass.png 404 (Not Found) 

So, the url the function loader.addImage() is trying to get the image from is incorrect.

My question

What is a good way to achieve what I'm trying to do? Should I build an ajax function that asks Codeigniter the base_url() and somehow use that in my JS?

Please help, I'm completely lost.

5
  • Post your loader.addImage code as well. Most likely the error is there. Commented Mar 11, 2013 at 20:47
  • stackoverflow.com/questions/12110144/… Commented Mar 11, 2013 at 20:48
  • Shouldn't it be GET localhost/index.php/user_data/grass.png ? Commented Mar 11, 2013 at 20:50
  • stackoverflow.com/questions/12110144/… – cillosis 1 min ago - This does not reallt address the problem of using a root url in the javascript as opposed to the html Commented Mar 11, 2013 at 20:50
  • I want it to be localhost/user_data/grass.png Commented Mar 11, 2013 at 20:52

1 Answer 1

1

I use this technique for posting config parameters to my js code from the backend:

In my layout file i output the following:

echo "<script>";
echo "window.myNameSpace = new Object(); ";
echo "window.myNameSpace.baseUrl = '" . base_url() . "';";
echo "</script>";

Then i am able to access this parameter in the js code whereever i want, like this:

var imageUrl = window.myNameSpace.baseUrl + image.png
Sign up to request clarification or add additional context in comments.

3 Comments

This will work. Is it standed practice to get access to servor config info in JS using your method?
I do not now if it can be considered standard practice but when I faced the same problem this was the best solution i could come up with. Compared to using an ajax request this is both faster and much more convenient.
You should use site_url() instead of base_url(), so the index page is included (when applicable).

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.