0

I have an index.php file that will load content based on a $_GET variable. So, it basically functions like this...

<?php
   $problem_id = $_GET['problem_id'];
   include('include/' . $problem_id . '.php');
?>

So, if a user clicks problem type #8, 8.php will be included in the index.php file and it's content will be displayed.

The problem is that I'm now using AJAX to load 8.php (or whatever file is selected). Some of the files depend on other javascript files (i.e. <script type="text/javascript" src="/include/js/api/utils.js"></script>) to work. It seems that these dependencies are not being loaded when I run the index.php file via AJAX. If I run it with a normal $_GET variable in the URL (i.e. http://myscript.com?problem_id=8), it works fine.

Is this a known issue with AJAX? Anyway around it?

Thanks.

4
  • Loading a php file based on a GET variable without checking for anything like that is very risky. I'd recommend against it. Commented Jun 18, 2014 at 21:40
  • 1
    The $_GET parameter is irrelevant, this is about how you're loading the AJAX response on the client. If you're just putting it in .innerHTML of an element, scripts will not be run. To get a dynamically loaded script to run, you have to create <script> elements explicitly in the loading code. Commented Jun 18, 2014 at 21:44
  • I have other protections in place. This was just a very small piece of the code for demonstration purposes. Commented Jun 18, 2014 at 21:45
  • See related question: stackoverflow.com/questions/8097026/… Commented Jun 18, 2014 at 21:47

1 Answer 1

2

You have not specified where the required javascript files are being loaded. However, if we assume they are being included by your php script, then yes they will work when you access that php script directly but when you include it via ajax they will not.

My suggestion which is the simple approach, is that in your calling page (index.php) you include all your javascript so that it is ready to go, regardless of which content is dynamically loaded in.

So load the dependencies always in advance, and don't include them in your included php files.

When you load content via ajax it really needs to be html which can be incorporated into the existing page DOM, it's not so straight forward to be loading javascript and executing it although that is possible (using requirejs or similar) but I think probably the above simple approach will work for you.

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

1 Comment

This is a good recommendation, which is why I'm not closing this as a duplicate of some of the other "Javascript via AJAX" questions.

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.