Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

About loading a script with AJAX 4

Status
Not open for further replies.

dkdude

Programmer
Jun 16, 2003
849
DK
Got : one html page with a DIV in it.

Works : I can load external files into that DIV using AJAX and a backend PHP script - say some html formatted stuff.

But : If the external file also contains some javascript code, then the AJAX'ed code won't run.

Example : Say a file I AJAX into my div looks like this
Code:
<script>

function tryme() {
  alert('Hello you!');
}

</script>

<button onclick="tryme()">Try me!</button>

I get an error when clicking the button.... this is confusing. How can I get this working?

Thanks
 
Hello Dk dude,

Did you find any solution to this problem , I am facing exactly same kind of a problem, would you please share yoru findings.

Thanks in advance

-Bob
 
Dude,

It seems that link only deals with the response that has pure js only in my case it has HTML as well as JavaScript like your first post, how did you handle html in the Ajax reponse, or how did you extract the Js from the response and set it dynamically ? Please advise..
 
Hey, I got it working now. Cool. Have a look at these files (BTW - I use PHP as server side).

The "ajax page" : index.html
Code:
<html>
<head>
  <title>AJAX - loads a new script!</title>
  <script type="text/javascript" src="ajax_lib.js"></script>
  <style type="text/css">
    #contents {
      width  : 500px;
      height : 100px;
      border : solid 1px #000;
    }
  </style>
</head>
<body>
  <a href="javascript:send_request('loadme.html')">Try me!</a>
  <hr />
  <div id="contents">
  </div>
</body>
</html>

The "javascript to be loaded" : new_script.js
Code:
function hello() {
  alert('Hello world');
}

The "ajax handler script" : ajax_lib.js
Code:
function createRequestObject() {
  var ro;
  var browser = navigator.appName;
  if(browser == "Microsoft Internet Explorer")
    ro = new ActiveXObject("Microsoft.XMLHTTP");
  else
    ro = new XMLHttpRequest();
  return ro;
}

function send_request(html_file_name) {
  server_side_script = 'html_loader.php?filename=' + html_file_name;
  http.open('get', server_side_script);
  http.onreadystatechange = handle_response;
  http.send(null);
}

var http = createRequestObject();

function handle_response() {
  if(http.readyState == 4){
    var response = http.responseText;
    var parts = response.split('[COLOR=red]~[/color]');
    if(parts.length>1) {
      load_script(parts[0]);
      document.getElementById('contents').innerHTML = parts[1];
    } else {
      document.getElementById('contents').innerHTML = response;
    }
  }
}

function load_script(filename) {
  var script = document.createElement('script'); 
  script.type = 'text/javascript'; 
  script.src = filename; 
  document.getElementsByTagName('head')[0].appendChild(script);
}

The "server side content loader" : html_loader.php
Code:
<?php
$file_name = $_REQUEST["filename"];
$html_file = file($file_name);
foreach($html_file as $lineno => $line)
  echo $line;
?>

The "content to be loaded" : loadme.html
Code:
new_script.js[COLOR=red]~[/color]<button onclick="hello()">Click me!</button>

The trick is this: before the char ~ is the name of the script to be loaded - after ~ is the html stuff. Replace ~ with any char you find best.

Hope this makes sense. It works for me :)

Good Luck
 
Bob, I guess this means you got it working too, huh? I'll make a FAQ then :)
 
Thanks, that looks very useful!

I solved a similar problem by extracting the javascript portion from the html on the server side (using ASP vbscript and regular expressions). Then I used JSON to pass back the html and the js as separate values. If the js value was not empty I eval'd it. It worked like a champ, but there was one gothca: you couldn't define a function like this:

function myFunc(params) { ... }

You had to define it like this:

myFunc = function(params) { ... };

It still works the same though.


Tracy Dryden

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard. [dragon]
 
Dude,

You have posted a very useful workaround to this problem, I am baout to implement it the way you suggested, but the thing that concerns me is that you create the script element in the original window/document, not in the div element that got dynamically populated.

In that case will it be possible for teh script to refer to teh elements in teh dynamically populated div element and manipulate/read their values ..please let me know.

-Bob F
 
It shouldn't be a problem. The div is part of the document, and div's don't have scripts, documents do.

Tracy Dryden

Meddle not in the affairs of dragons,
For you are crunchy, and good with mustard. [dragon]
 
he reason I said so is that the div elements gets populated with the whole jsp , it has a button and javascript that comes along with the jsp , now I have to make sure that js gets called on the click of the button , I tried including the js in the original document and it was not able to refer to the elements in the dynamically populated div..
 
Bob,

Actually this loads the new JavaScript in the html head dynamically.

So, yes, you would have to make sure the new script only affects the stuff intended; in the target DIV - but then again, the JS is kind of global to the active document, so I see no way of avoiding this.

Except for the abvious -you're in control, of what get's loaded and how it works, right?

Hope this works for you still. If not - just get back. We'll work something out ;-)

Regards


Jakob
 
Jeff, excellent tip. I'll have a looksee at "Jason" soon ... ;-)

Cheers
 
Dude,

Looks like its too much of a hassle when we have something like Prototype , I am going with Prototype for now, becuase I am using portal which dynamically genereates js, which I have no control over, thanks for your help though, I really appreciate that...
 
Hello Jakob,

This is Bob again, your solution works fine when the javascript code has a reference to a file but, can you think of any solution if the retunred response has the actual javascript code in the returned document like <script></script>.The problem is in this case you cant use

script.src = filename;

Can anybody let me know any work around to this problem??

Thanks in Advance!!
 
Hello again, Bob.

I am not a real guru on DOM, but it would seem to me that you could set the innerHTML attribute of the created script element to the text that is returned.

Tom Morrison
 
Hi Bob,

I like Tom's idea .. that could be what you're looking for?

Are you using PHP for server side stuff? I am. I'm thinking that one approach would be to extract the <script> // js stuff </script> and let PHP serve a "virtual external .js" that could be loaded ... would that be a useful solution for you?

Cheers


Jak:)b
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top