Metnetsky <mi******@syr.edu> wrote in message news:<pa****************************@syr.edu>...
I'd like to build a function that is executed when someone clicks on an
image. Once clicked, I need some parameters passed to a URL which PHP
will accept and deal with database connections. Sounds simple, and is
simple. The only thing that stumps me is that I do not want that PHP page
loaded anywhere that someone would see it. And preferably no frames if
possible.
Any suggestions?
Sure. The <script> element allows you to specify a URL in the src
attribute. Most people just put [somefile].js, but it can actually be
something like "getCustomerData.php?nameToFind=met&searchType=lea ding".
The key is that the PHP page (or ASP, JSP, or whatever) must return
JavaScript, not HTML, because it is going to be fed to the JavaScript
interpreter. That solves the first problem, which is how to get
information from the server to the page without causing it to refresh.
The next problem is how to dynamically invoke that method.
var nameSearchElement;
var nameSearchResult;
function doNameSearch ( nameToSearch ) {
if ( nameSearchElement != null ) {
document.body.removeChild ( nameSearchElement );
nameSearchElement = null;
}
nameSearchElement = document.createElement ( "SCRIPT" );
nameSearchElement.src = "getCustomerData.php?nameToFind=" +
encodeURIComponent ( nameToSearch ) + "&searchType=leading";
document.body.appendChild ( nameSearchElement );
}
function doNameSearchComplete ( ) {
// process the nameSearchResult object
}
The doNameSearch function creates the script element, attaches it to
the current document, which in turn causes the browser to ask the
server for the source of the script element. This establishes
communication back to the server and allows you to retrieve the
results.
The server code must return valid JavaScript code. In this example, I
have created a global variable "nameSearchResult" so I know where to
look for the results of the search. It is up to you to define how to
structure that data. This example also defines a callback function,
"doNameSearchComplete", used to signal that the operation is complete.
So, for example, the page could generate the following code:
nameSearchResult = {
numNamesFound: 0,
error: "Database currently unavailable"
};
doNameSearchComplete ( );
The last line invokes the callback function, indicating that the
server roundtrip is complete. Unfortunately, the database was down...
The good thing about this process is that it does not require
plug-ins, ActiveX objects, proprietary calls to internal components,
etc. Just good, old DHTML. The extra sweetener is that you get raw
data as executable code, not HTML or XML that has to be parsed and
then reformatted by other code.
Hope that helps.