PDA

View Full Version : Javascript in PHP includes (AJAX)


trs4ece
12-17-2009, 04:33 AM
I am working on learning AJAX for a web design project and have run into a problem with PHP includes. I essentially have a PHP AJAX page that pulls in one of three different PHP AJAX pages depending on the menu selection. It pulls in the HTML content just fine but when I try to run the AJAX from the imported page, I see an error that the javascript functions associated with that page do not exist. Is there something else that I should do to pull in these pages properly?

Here's some excerpts of the code that I'm using:

index.html<script src="index.showEx.js"></script>
</head>
<body>

<form>
Select an example:
<select name="examples" onchange="showEx(this.value)">
<option value="CD Database">CD Database</option>
<option value="Get Time">Get Time</option>
<option value="Name Hint">Name Hint</option>
</select>
</form>

<span id="showEx"></span>

index.showEx.jsvar xmlhttp

function showEx(str){
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null){
alert ("Your browser does not support AJAX!");
return;
}
var url="index.showEx.php"+"?q="+str+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged(){
if (xmlhttp.readyState==4){
document.getElementById("showEx").innerHTML=xmlhttp.responseText;
}
}

function GetXmlHttpObject(){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject){
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}


index.showEx.php<?php
$q=$_GET["q"];
if ($q == "CD Database"){
include "CDDatabase.html";
}
else if ($q == "Get Time"){
include "getTime.html";
}
else if ($q == "Name Hint"){
include "nameHint.html";
}
?>


And here is one of the files to be included. They're each setup pretty much in the same style as the index page.

nameHint.html<!--
TITLE: AJAX Name Hint
FUNCTION: Searches an array for matching strings based on typed input
-->
<html>
<head>
<title>AJAX Name Hint</title>
<script src="nameHint.clientHint.js"></script>
</head>
<body>

<form>
First Name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>

</body>
</html>

Fou-Lu
12-17-2009, 04:38 AM
Definitely not a Java problem, and also not a problem with PHP. Moving from Java to Javascript.

The client side guys may benefit more from a direct link to you're site than the code posted. The only potential PHP problem here is if the querystring has not been encoded.

trs4ece
12-17-2009, 04:42 AM
Thanks, new to these forums and didn't see the AJAX subsection. Here's a link to the code as it is right now:

http://author.www.purdue.edu/bands/d9/ajax/