0

I'm writing an AJAX page with php, which will echo a block of JS code when it finishes. Although the JS code is embedded into HTML page, it doesn't work. How can I make it work?

Lazy_Clutch
  • 130
  • 3
  • 14

2 Answers2

5

Browsers generally don't execute js in ajax sections, for security reasons.

You'll want to provide the final javascript to be executed in a callback to the ajax load functionality instead.

Even better, just include the javascript from the target page in an external initialization function (e.g. function finalizeProfilePage()) in some siteName.js file and then load that upon completion of the ajax load and where-ever else you use that page content.

Kzqai
  • 22,588
  • 25
  • 105
  • 137
  • really!?!? actually i'm right now coding something like this and it works! – nowhere Jun 18 '13 at 11:53
  • Would it be bad of me to mention `eval()` right now ? :) `eval(responseScript)` would actually work :) – Damien Overeem Jun 18 '13 at 12:00
  • 5
    @damien you just risk getting kidnapped by a three-headed evil chicken. – Sumurai8 Jun 18 '13 at 12:03
  • Thanks! I added the code in the callback and it successfully works! – Lazy_Clutch Jun 18 '13 at 12:03
  • @Sumurai8 Can it be a 3-assed chicken instead? 3x the eggs.. i love eggs. – Damien Overeem Jun 18 '13 at 12:08
  • @CosLu Usually the way it works is defined functions are made available but procedural execution is not done, so perhaps that's what you're seeing? I'm not really sure of the full rules for allowing function definitions but not function execution within ajax loads, but overall, why worry about all that instead of just externalizing the javascript more cleanly anyway, and then using a callback becomes trivial. – Kzqai Jun 18 '13 at 12:11
  • @Damien Overeem, Yeah, shhhhhh, don't speak of eval(), if someone finds that dirty method themselves, then let them reap their *final reward* on their own. :p – Kzqai Jun 18 '13 at 12:13
-1

I'm right now working on something similar. To execute the code loaded through ajax i just need to call the function like this:

jQuery(function() {
        loadScript();
    });

(yes i'm using jquery )

nowhere
  • 1,558
  • 1
  • 12
  • 31