I have a section on my web page that is loaded using ajax - a php script that generates the needed HTML output. as part of the content that is loaded I also load values that I need to access using javascript. So the HTML I generate includes a section like: <script language='javascript'> var a =1; var b=2; </script> After outputting the HTML returned via ajax, the variables defined in the JS section are not recognized and I get an error stating the variables aren't defined. Why is this? Any solutions?
What's the code where you perform the actual ajax? Becuase in most cases the return is only evaluated as text, and javacript wouldn't automatically be run because the page had already been loaded. For situations like these JQuery has a function called getScript, which not only grabs the content from another file but executes it as javascript once retrived. example: $.getScript("test.js"); Code (markup): except in your case you'd put the php file name there, and the echo shouldn't contain the <script lines, since its expecting the same format you'd use for a .js file.
thanks. you're right, the ajax really did evaluate the script as text. I thought maybe there was an easier way than splitting into two calls.
also, keep in mind scoping, I have had problems like this coming from ajax for example, if you have: var myfunction() { alert(foobar); }; var myAjax = function() { new Request({ onComplete: function() { // returns and evaluates the equivalent of: var foobar = "hello!"; // foobar will be hello in this anonymous scope only. } } }; myAjax(); // later on call, after a click or something, myfunction: myfunction(); // won't alert 'hello' unless set from somewhere else PHP: so make sure you declare your variables within the global (or relevant) scope. best to use a global namespace like: var mySite = { foobar: "" } // always defined // ajax to eval: mySite.foobar = "hello"; PHP: regards,