#native_company# #native_desc#

Calling a PHP function from JavaScript…..sort of.

By David Norton
on April 4, 2005

Yes, I know. It’s impossible to call a PHP function directly from JS. But that doesn’t mean we can’t cheat a bit!

Let’s assume you have a javascript variable that must be passed to a php script for back-end processing (it happens sometimes!) Try opening an iframe and passing the javascript variable in the url (sounds too simple, but there’s more…!)

…you don’t want that ugly iframe hanging around, visible to your users, so you can close it by removing the node.

Here’s a dirty example:

//create a js variable that contains the url and js variables to be passed.

var myUrl="http://***.***.***.***/func.php?var1="+text1.value+"&"+"var2="+text2.value;

//insert this as the value of the .src property of your iframe element:

var iframe1=document.createElement("iframe");

(if you need more help understanding creating html elements as javascript elements, contact me)

//next, remove the element node from the document so the users won’t see the iframe.


This has worked well for me in creating an application management ui that is constructed with only javascript (no html at all/big advantages!). Each “link” that presents the user with a new admin interface is actualy only a new function that creates and positions the javascript elements (input, text, button, img, etc.) on the document and adds event listeners and event handlers to process the user input. For instance; a public key/private key script where the user enters a user name and password into two text elements (not an html form) is then passed directly to a javascript function for client-side validation.
The quickest, cleanest next step was to pass this data directly (or as closely thereto) to a php script, unnoticed by the user, for server-side processing.

A return from the php script to the client browser can be made ie,

?><script>alert("A user name is required");</script><?

, if back-end validation is done.

This works well in IE5.x and NN7.x.