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.

gtilflm
  • 1,389
  • 1
  • 21
  • 51
  • Loading a php file based on a GET variable without checking for anything like that is _very_ risky. I'd recommend against it. – Benjamin Gruenbaum Jun 18 '14 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 ` – Barmar Jun 18 '14 at 21:44
  • I have other protections in place. This was just a very small piece of the code for demonstration purposes. – gtilflm Jun 18 '14 at 21:45
  • See related question: http://stackoverflow.com/questions/8097026/how-to-run-javascript-in-html-loaded-via-ajax?rq=1 – Barmar Jun 18 '14 at 21:47

1 Answers1

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.

Action Dan
  • 443
  • 4
  • 10
  • 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. – Barmar Jun 18 '14 at 21:48