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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to load a new JavaScript with AJAX and PHP

AJAX with PHP backend

How to load a new JavaScript with AJAX and PHP

by  dkdude  Posted    (Edited  )
So you want to load a new script the AJAX way?

This FAQ tells you how to do it with a PHP backend script. The backend script language doesn't really matter - this should give you the basic idea.

Here's what you have:

0) A server with a PHP
1) Some HTML formatted stuff
2) Some JavaScript in an external file you need to load with the HTML stuff

It takes a few files to spin it off. The flow goes like this:

A user clicks a link. This link fires a JavaScript. The JavaScript requests a specific file from a server side backend script. The backend script returns a string (or more). The return is splitted in to two parts. One part is the name of the external JavaScript to be loaded; another is the HTML formattet output to be inserted in your AJAX page.

This example assumes that the target of the HTML stuff is a DIV id'd 'contents'.

You need five files to complete this example

1) The base page
2) The JavaScript to be loaded
3) The AJAX handler
4) A server side backend to load the new content and -JavaScript
5) "The" new file - JavaScript filename reference AND HTML formatted return

So here's the code ...

1: "Base page" : [tt]index.html[/tt]
Code:
[b]<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>[/b]

2: "JavaScript to be loaded" : [tt]new_script.js[/tt]
Code:
[b]function hello() {
  alert('Hello world');
}[/b]

3: "AJAX handler" : [tt]ajax_lib.js[/tt]
Code:
[b]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);
}[/b]

4: "Server side backend" - in this example a PHP script : [tt]html_loader.php[/tt]
Code:
[b]<?php
$file_name = $_REQUEST["filename"];
$html_file = file($file_name);
foreach($html_file as $lineno => $line)
  echo $line;
?>[/b]

5: "Formatted file - Script file name & HTML stuff" : [tt]loadme.html[/tt]
Code:
[b]new_script.js[color red]~[/color]<button onclick="hello()">Click me!</button>[/b]

Please note that in this example, the char [color red]~[/color] in the "Formatted file - Script file name & HTML stuff" is used to separate the script filename from the HTML formatted stuff. You may want or need to change the char [color red]~[/color] to something else. If you do, you need to change it i in both [tt]loadme.html[/tt] and [tt]ajax_lib.js[/tt].

Happy coding


Jak:)b
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top