« Previous entry | Next entry » Browse > Snippets
Skip to comments (8)
javascript to php function calls
Posted by Erik on Jan 02 2006 @ 12:55 :: 6307 unique visits
With all the AJAX hype lately I created these simple javascript to php function call scripts.usage
in your javascript:
fn_call(name, return, arg1, arg2, ...);
name is the function name to call.
return is the function which should handle the return value.
arg* the arguments for the php function
fn_url should contain the php file which contains the function (default is the current url).
fn_debug can be set to true for debug messages.
in your php code all functions which start with fn_ are callable (see example below).
How does it work
The script just simply converts all javascript variables to a post sting which php automatically converts to the right php variables.
The return value of your php function is converted to a javascript variable which is passed to the return handler.
fn.inc.php
CODE: PHP
<?
// fn.inc.php v1.1 by Erik
function __fn_string($var) {
// because eval won't handle multiline string we have to convert the \n
$var = addslashes($var);
return str_replace("\n", '\n', $var);
}
// convert a php variable to a javascript variable
function __fn_tojs($name, $var) {
if (is_int($var)) {
echo $name.' = '.$var.';';
} else if (is_float($var)) {
echo $name.' = '.sprintf('%f', $var).';';
}
else if (is_bool($var)) {
if ($var) {
echo $name.' = true;';
} else {
echo $name.' = false;';
}
}
else if (is_array($var)) {
echo $name.' = new Array();';
foreach ($var as $i => $e) {
if (is_string($i)) {
$i = '"'.__fn_string($i).'"';
}
else if (is_bool($i)) {
if ($i) {
$i = 'true';
} else {
$i = 'false';
}
}
__fn_tojs($name.'['.$i.']', $e);
}
}
else if (is_string($var)) {
echo $name.' = "'.__fn_string($var).'";';
}
else if (is_null($var)) {
echo $name.' = null;';
}
else if (is_object($var)) {
echo $name.' = "'.__fn_string(serialize($var)).'";';
}
else {
// $r is a resource which can't be returend in any way
echo $name.' = "resource";';
}
}
function __fn_error($msg) {
die('/* '.$msg.' */ '); // comments to eval won't error
}
function __fn_handler() {
$func = 'fn_'.$_POST['fn'];
// check if the function is user defined
$ufuncs = get_defined_functions();
if (array_search($func, $ufuncs['user']) === false) {
__fn_error('unknown function');
}
// are we interrested in the return value?
$iret = isset($_POST['ret']) ? $_POST['ret'] : 0;
// unset these so only the arguments are left (easyer for the foreach)
unset($_POST['fn']);
unset($_POST['ret']);
// use an @ so we won't get any warnings about argument count mismatch
$r = @call_user_func_array($func, $_POST);
if ($iret) {
__fn_tojs('fn_ret', $r);
} else {
echo '/* not interrested */ ';
}
}
function fn_iscall() {
return isset($_POST['fn']);
}
if (fn_iscall()) {
register_shutdown_function('__fn_handler');
}
?>
// fn.inc.php v1.1 by Erik
function __fn_string($var) {
// because eval won't handle multiline string we have to convert the \n
$var = addslashes($var);
return str_replace("\n", '\n', $var);
}
// convert a php variable to a javascript variable
function __fn_tojs($name, $var) {
if (is_int($var)) {
echo $name.' = '.$var.';';
} else if (is_float($var)) {
echo $name.' = '.sprintf('%f', $var).';';
}
else if (is_bool($var)) {
if ($var) {
echo $name.' = true;';
} else {
echo $name.' = false;';
}
}
else if (is_array($var)) {
echo $name.' = new Array();';
foreach ($var as $i => $e) {
if (is_string($i)) {
$i = '"'.__fn_string($i).'"';
}
else if (is_bool($i)) {
if ($i) {
$i = 'true';
} else {
$i = 'false';
}
}
__fn_tojs($name.'['.$i.']', $e);
}
}
else if (is_string($var)) {
echo $name.' = "'.__fn_string($var).'";';
}
else if (is_null($var)) {
echo $name.' = null;';
}
else if (is_object($var)) {
echo $name.' = "'.__fn_string(serialize($var)).'";';
}
else {
// $r is a resource which can't be returend in any way
echo $name.' = "resource";';
}
}
function __fn_error($msg) {
die('/* '.$msg.' */ '); // comments to eval won't error
}
function __fn_handler() {
$func = 'fn_'.$_POST['fn'];
// check if the function is user defined
$ufuncs = get_defined_functions();
if (array_search($func, $ufuncs['user']) === false) {
__fn_error('unknown function');
}
// are we interrested in the return value?
$iret = isset($_POST['ret']) ? $_POST['ret'] : 0;
// unset these so only the arguments are left (easyer for the foreach)
unset($_POST['fn']);
unset($_POST['ret']);
// use an @ so we won't get any warnings about argument count mismatch
$r = @call_user_func_array($func, $_POST);
if ($iret) {
__fn_tojs('fn_ret', $r);
} else {
echo '/* not interrested */ ';
}
}
function fn_iscall() {
return isset($_POST['fn']);
}
if (fn_iscall()) {
register_shutdown_function('__fn_handler');
}
?>
fn.js
CODE: JAVASCRIPT
// fn.js v1.0 by Erik
var fn_debug = false;
var fn_url = document.location.href;
function __fn_req() {
// http://www.codepost.org/browse/snippets/59
var types = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.5.0',
'MSXML2.XMLHTTP.4.0',
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP'
];
for (var i = 0; i < types.length; i++) {
try {
return new ActiveXObject(types[i]);
} catch(e) {}
}
try {
return new XMLHttpRequest();
} catch(e) {}
return false; // XMLHttpRequest not supported
}
// convert a javascript variable to a php post argument
function __fn_topost(n, v) {
var t = typeof v;
if (t == 'number') {
return '&'+n+'='+v;
}
else if (t == 'boolean') {
if (v) {
return '&'+n+'=1';
} else {
return '&'+n+'=0';
}
}
else if (t == 'object') {
if (v == null) { // null seems to be an object
return '&'+n+'=null';
} else if (v.constructor == Array) {
var ret = '';
var len = v.length;
for (var i = 0; i < len; i++) {
if (v[i] == null) { // __fn_topost(v[i]) will cause a warning
ret += '&'+n+'['+i+']=null';
} else {
ret += __fn_topost(n+'['+i+']', v[i]);
}
}
return ret;
} else {
return '&'+n+'='+escape(v.toString());
}
}
/* this is not needed as the else case does teh same
else if (t == 'function') {
return '&'+n+'='+escape(v.toString());
}*/
else {
return '&'+n+'='+escape(v);
}
}
function __fn_call(debug, args) {
var req = __fn_req();
if (typeof req == 'boolean') {
if (debug) {
alert('--fn-debug--\nXMLHttpRequest not supported');
}
} else {
var post = 'fn='+args[0];
var wret = 0;
if ((typeof args[1] == 'function') ||
(typeof args[1] == 'string')) {
wret = 1; // we are interrested in the return value
} else if (debug) {
wret = 1;
}
post += '&ret=' + wret;
// construct all the arguments
var alen = args.length;
for (var i = 2; i < alen; i++) {
post += __fn_topost(i-2, args[i]);
}
// need to do something with the return value?
if (wret) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
if (debug) {
var prnt = req.responseText;
prnt = prnt.replace(/;/g, ';\n');
prnt = prnt.replace(/\\n/g, '\n');
alert('--fn-debug--responseText--\n'+prnt);
}
var fn_ret = false;
try {
eval(req.responseText);
} catch(e) { }
if (typeof args[1] == 'function') {
args[1](fn_ret);
} else if (typeof args[1] == 'string') {
eval(args[1]);
}
} else {
if (debug) {
alert('--fn-debug--statusText--\n'+req.statusText);
}
}
}
};
}
if (debug) {
alert('--fn-debug--post--\n'+post.replace(/&/g, '\n&'));
}
req.open('POST', fn_url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send(post);
}
}
function fn_call() {
__fn_call(fn_debug, arguments);
}
function fn_call_debug() {
__fn_call(true, arguments);
}
var fn_debug = false;
var fn_url = document.location.href;
function __fn_req() {
// http://www.codepost.org/browse/snippets/59
var types = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.5.0',
'MSXML2.XMLHTTP.4.0',
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP'
];
for (var i = 0; i < types.length; i++) {
try {
return new ActiveXObject(types[i]);
} catch(e) {}
}
try {
return new XMLHttpRequest();
} catch(e) {}
return false; // XMLHttpRequest not supported
}
// convert a javascript variable to a php post argument
function __fn_topost(n, v) {
var t = typeof v;
if (t == 'number') {
return '&'+n+'='+v;
}
else if (t == 'boolean') {
if (v) {
return '&'+n+'=1';
} else {
return '&'+n+'=0';
}
}
else if (t == 'object') {
if (v == null) { // null seems to be an object
return '&'+n+'=null';
} else if (v.constructor == Array) {
var ret = '';
var len = v.length;
for (var i = 0; i < len; i++) {
if (v[i] == null) { // __fn_topost(v[i]) will cause a warning
ret += '&'+n+'['+i+']=null';
} else {
ret += __fn_topost(n+'['+i+']', v[i]);
}
}
return ret;
} else {
return '&'+n+'='+escape(v.toString());
}
}
/* this is not needed as the else case does teh same
else if (t == 'function') {
return '&'+n+'='+escape(v.toString());
}*/
else {
return '&'+n+'='+escape(v);
}
}
function __fn_call(debug, args) {
var req = __fn_req();
if (typeof req == 'boolean') {
if (debug) {
alert('--fn-debug--\nXMLHttpRequest not supported');
}
} else {
var post = 'fn='+args[0];
var wret = 0;
if ((typeof args[1] == 'function') ||
(typeof args[1] == 'string')) {
wret = 1; // we are interrested in the return value
} else if (debug) {
wret = 1;
}
post += '&ret=' + wret;
// construct all the arguments
var alen = args.length;
for (var i = 2; i < alen; i++) {
post += __fn_topost(i-2, args[i]);
}
// need to do something with the return value?
if (wret) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
if (debug) {
var prnt = req.responseText;
prnt = prnt.replace(/;/g, ';\n');
prnt = prnt.replace(/\\n/g, '\n');
alert('--fn-debug--responseText--\n'+prnt);
}
var fn_ret = false;
try {
eval(req.responseText);
} catch(e) { }
if (typeof args[1] == 'function') {
args[1](fn_ret);
} else if (typeof args[1] == 'string') {
eval(args[1]);
}
} else {
if (debug) {
alert('--fn-debug--statusText--\n'+req.statusText);
}
}
}
};
}
if (debug) {
alert('--fn-debug--post--\n'+post.replace(/&/g, '\n&'));
}
req.open('POST', fn_url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send(post);
}
}
function fn_call() {
__fn_call(fn_debug, arguments);
}
function fn_call_debug() {
__fn_call(true, arguments);
}
Example usage
example.php
CODE: PHP
include './fn.inc.php';
function fn_hello($name) {
return "hello $name";
}
function fn_hello($name) {
return "hello $name";
}
somewhere in your javascript
CODE: JAVASCRIPT
fn_url = 'example.php'; // only needs to be set once somewhere
...
function theresult(str) {
alert(str);
}
fn_call('hello', theresult, 'erik');
...
function theresult(str) {
alert(str);
}
fn_call('hello', theresult, 'erik');
8 comments posted so far
Add your own »
2. On Jan 19 2006 @ 12:01 Erik wrote:
Added a try-catch block around the eval() of the responseText to ignore PHP errors.CODE: JAVASCRIPT
var fn_ret = false;
try {
eval(req.responseText);
} catch(e) { }
try {
eval(req.responseText);
} catch(e) { }
To find these errors set fn_debug = true; and you will see the responseText.
3. On Mar 09 2006 @ 14:59 guest wrote:
Why in the name of good god, the script (javascript) return false even if I don´t have a return FALSE in PHP function???4. On Mar 09 2006 @ 17:55 Erik wrote:
Show us your code so we can see.5. On Jul 09 2006 @ 04:24 guest wrote:
thats bullshit man6. On Aug 17 2006 @ 16:44 guest wrote:
i want to call function whenever we click on combo button..7. On Sep 15 2006 @ 21:41 guest wrote:
msxml6.0 was released. Add this to your code 'MSXML2.XMLHTTP.6.0'.Why do you care to do that? bceause msxml6.0 will deprecate msxml4.0 sooner or later. Also msxml5.0 should not be used, since it is not a publically released version.
-
8. On Aug 09 2008 @ 05:24 priya wrote:
Anyone bought from www.belrion.com before ? heard they are a paypal world seller and are macfee secured. Appreciate some feedback from anyone ^^<a href = http://www.belrion.com/en/ffxi.htm > buy ffxi</a><br>
<a href = http://www.belrion.com/en/eq.htm> buy eq flat </a><br>
<a href = http://www.belrion.com/en/wow.htm> cheap wow gold</a><br>
<a href = http://www.belrion.com> LOTR gold</a><br>
<a href = http://www.belrion.com/en/sell.htm>buy aoc gold</a><br>
<a href = http://www.belrion.com/en/l2.htm> buy L2 adena</a><br>
<a href = http://www.belrion.com/en/gamesvr.php?cid=1&gid=3&sid=10 >buy gils</a><br>
<a href = http://www.belrion.com/en/eq.htm >cheap gold wow</a><br>
1. On Jan 10 2006 @ 10:03 Erik wrote:
As noted by Niek the following code would change the floating point number 1.0 into an integer 1echo $name.' = '.$var.';';
}
So I changed it to:
echo $name.' = '.$var.';';
} else if (is_float($var)) {
echo $name.' = '.sprintf('%f', $var).';';
}