Hi All,

Some website said the we cannot run php function in javascript because php is on server side and javascript is on client side.

My code will help us to run a php function when you type something on the textbox given below.

<?php
function myfunction(){
$x="I love PHP  by Arman de Guzman de Castro :-)!";
return $x;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script language="javascript" type="text/javascript">
function ILovePHP() {
b = "<?=myfunction();?>";
alert(b);
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<form action="" method="post"><input name="" name="" type="text" onChange="ILovePHP();"></form><p>
</body>
</html>

try this!!

cheers!!!

Recommended Answers

All 19 Replies

not possible the way you are doing it. you are displaying the output of that function in a js variable.

php is writing the javascript. javascript did not call the php function.

the only way you can do that is by ajax.

I agree with kkeith29 because below is an example of what happens when you put real php in the function:

<?php
function myfunction(){
die("The script has now ended.");
return 0;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script language="javascript" type="text/javascript">
function ILovePHP() {
b = "<?=myfunction();?>";
alert(b);
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<form action="" method="post"><input name="" name="" type="text" onChange="ILovePHP();"></form><p>
</body>
</html>

If you try running the script above, the php die() function will end the script before the page is loaded instead of on the onchange event. The reason, the php function is being executed before the page is loaded weather there is an onchange event or not.

Hi Guys!

let's talk about the output...okay!... What is the output when you run the program?

here's the output: "I love PHP by Arman de Guzman de Castro :-)!" right?


meaning when you call b = "<?=myfunction();?>"; the java run the PHP myfunction(). Because if the output is like this "NULL/EMPTY" meaning you cannot execute php on javascript this will not show you any value right?.

<?php
function myfunction(){
$x="I love PHP by Arman de Guzman de Castro :-)!";
return $x;
}

Thanks for you comments guys....I will try some complex example....regarding this...I haven't try this yet to return the records inside the database...

Well the only problem if your example is that the function will execute when the page loads and not when it is called. So say you had a mysql query that inserts something into a database when the function is called. You will find that before the page is finnished loading, the value would have been inserted into the mysql database even though the user hasn't done anything to call the function. So your method may sometimes work for data output but never for data input.

Well the only problem if your example is that the function will execute when the page loads and not when it is called. So say you had a mysql query that inserts something into a database when the function is called. You will find that before the page is finnished loading, the value would have been inserted into the mysql database even though the user hasn't done anything to call the function. So your method may sometimes work for data output but never for data input.

<?php
function myfunction(){
define('MYTXT',"the quick brown fox");
define('MYTXT2',"jumps over the lazy dog.");
$x=MYTXT . MYTXT2;
return $x;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script language="javascript" type="text/javascript">
function ILovePHP() {
b = "<?=myfunction();?>";
alert(b);
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<form action="" method="post"><input name="" name="" type="text" onChange="ILovePHP();"></form><p>
</body>
</html>

I put some constant value...

you will see...the function is working....in that case...you can run back the javascript inside the php function because..php can execute javascript right?

you can get the return value of the php function and put it into array() inside your javascript right?...

I hope we can improve this code...in the future....:-)

Then heres another example to show that for input it won't work:

<?php
function myfunction(){
mysql_query('INSERT INTO `table` SET `column`="value"') or die(mysql_error());
return 0;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script language="javascript" type="text/javascript">
function ILovePHP() {
b = "<?=myfunction();?>";
alert(b);
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<form action="" method="post"><input name="" name="" type="text" onChange="ILovePHP();"></form><p>
</body>
</html>

If you check the above example, the mysql query cannot be ran more than once and will only ever be ran when the page loads.

Then heres another example to show that for input it won't work:

<?php
function myfunction(){
mysql_query('INSERT INTO `table` SET `column`="value"') or die(mysql_error());
return 0;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script language="javascript" type="text/javascript">
function ILovePHP() {
b = "<?=myfunction();?>";
alert(b);
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<form action="" method="post"><input name="" name="" type="text" onChange="ILovePHP();"></form><p>
</body>
</html>

If you check the above example, the mysql query cannot be ran more than once and will only ever be ran when the page loads.

so it works!!! right? meaning...you can run php function() in javascript because you can insert the data... Can you try foreach() to loop it.

actually friend we are not after of loading page or something etc...etc... my main concern is running a php function when you trigger and event in javascript. so it up to us to explore more on my example and think on more unique coding if can help us or not in doing php website.

thx friend.

Well what I can't stress enough is that javascript doesn't trigger the php event. It just retrieves the results from the function being triggered during the page load. Below is an example based on your first example the explains more of what is happening:

<?php
$x="I love PHP  by Arman de Guzman de Castro :-)!";
$returnstring=$x;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script language="javascript" type="text/javascript">
function ILovePHP() {
b = "<? echo $returnstring; ?>";
alert(b);
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<form action="" method="post"><input name="" name="" type="text" onChange="ILovePHP();"></form><p>
</body>
</html>

The above example does exactly the same thing as the example on post #1. The only difference is a few lines are written differently to make it look more realistic/better.

Then heres another example to show that for input it won't work:

<?php
function myfunction(){
mysql_query('INSERT INTO `table` SET `column`="value"') or die(mysql_error());
return 0;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script language="javascript" type="text/javascript">
function ILovePHP() {
b = "<?=myfunction();?>";
alert(b);
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<form action="" method="post"><input name="" name="" type="text" onChange="ILovePHP();"></form><p>
</body>
</html>

If you check the above example, the mysql query cannot be ran more than once and will only ever be ran when the page loads.

run this code and you will see error prompt in php....

function ILovePHP() { b = "
Warning: mysql_query() [function.mysql-query]: Access denied for user 'ODBC'@'localhost' (using password: NO) in C:\TESTING SERVER\htdocs\admin_drafts\test.php on line 4

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in C:\TESTING SERVER\htdocs\admin_drafts\test.php on line 4
Access denied for user 'ODBC'@'localhost' (using password: NO)

you try to remove the alert(b) still it will give you the php error message...meaning....
the javascript run the php function right?.....

CONCLUSION: If you put any php function in javascript variable using my format ( b = "<?=myfunction();?>"; ) this will run the php function first...before assigning on that variable (b)...

Never thought I would have to explain that but it is because you didn't set the database connection and ya probably didn't create the table too. More info about that can be found at http://www.tizag.com/mysqlTutorial/mysqlconnection.php

this example will show that what you are trying to say is true is actually false. you cannot call a php function in javascript.

<?php

function echoString() {
    echo 'Function ran';
}

?>
<html>
<head>
<title>Testing</title>
</head>
<body>
<form action="" method="post"><input name="" name="" type="text" onChange="echoString();"></form>
</body>
</html>

not possible. you can only use the output of the php function on its initial call. So when ILovePHP() was called in your earlier example it wasn't calling the php function again.

<?php
function myfunction(){
define('MYTXT',"the quick brown fox");
define('MYTXT2',"jumps over the lazy dog");
$x=ucwords(MYTXT . MYTXT2);
return $x;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script language="javascript" type="text/javascript">
function ILovePHP() {
b = "<?=myfunction();?>";
alert(b);
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<form action="" method="post"><input name="" name="" type="text" onChange="ILovePHP();"></form><p>
</body>
</html>

let's use "ucwords() function ...Uppercase the first character of each word in a string.

it works!!!

Never thought I would have to explain that but it is because you didn't set the database connection and ya probably didn't create the table too. More info about that can be found at http://www.tizag.com/mysqlTutorial/mysqlconnection.php

no need to explain friend i know that it is not complete :-)... I just want to show you...that...it will run the php function first...:-)

yeah. obviously. that is how php works. ????? why did you post this again.

That is one of the most basic things of php.

this example will show that what you are trying to say is true is actually false. you cannot call a php function in javascript.

<?php

function echoString() {
    echo 'Function ran';
}

?>
<html>
<head>
<title>Testing</title>
</head>
<body>
<form action="" method="post"><input name="" name="" type="text" onChange="echoString();"></form>
</body>
</html>

not possible. you can only use the output of the php function on its initial call. So when ILovePHP() was called in your earlier example it wasn't calling the php function again.

may be...in the future...we can use...some code to run that...like maybe...you can include('file'); with echo command...:-)

thx guys....

so our what is your conclusion now?

CAN RUN OR NOT? :-)

Well the php code will allways run when the page firsts loads and not when javascript or html calls it. However, by saying that, javascript can still display the data that was proccessed during the loading of the page but not displayed in the first place.

//RUN THIS IN YOUR MYSQL

CREATE TABLE `php_to_js` (
  `srno` int(11) NOT NULL auto_increment,
  `u_name` varchar(50) default NULL,
  `u_email` varchar(55) default NULL,
  PRIMARY KEY  (`srno`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records 
-- ----------------------------
INSERT INTO `php_to_js` VALUES ('1', 'name1', 'name1@yahoo.com');
INSERT INTO `php_to_js` VALUES ('2', 'name2', 'name2@yahoo.com');
INSERT INTO `php_to_js` VALUES ('3', 'name3', 'name3@yahoo.com');
INSERT INTO `php_to_js` VALUES ('4', 'name4', 'name4@yahoo.com');
INSERT INTO `php_to_js` VALUES ('5', 'name5', 'name5@yahoo.com');

==================================================================
'name the file below javatomysql.php'

<html>
<head>
<script language="JavaScript"><!--
//these function from:
//http://www.devshed.com/c/a/PHP/PHP-and-JavaScript-Pooling-Your-Resources/
//this function calls the child file
function attach_file( p_script_url ) {
// create new script element, set its relative URL, and load it
script = document.createElement( 'script' );
script.src = p_script_url;
document.getElementsByTagName( 'head' )[0].appendChild( script );
}

//this function updates the status box
function show_status( status_text ) {
document.getElementById('status').innerHTML = status_text;
}
//-->
</script>
<title>PHP MySQL and Javascripts Working Together </title>
<!-- CSS Details -->
<style type="text/css">
<!--
.table1 {
border: 1px solid #CC6600;
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 10px;
font-style: normal;
text-transform: none;
}
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 8px;
background-position: center top;
margin: 0px;
padding: 15px;
}
input {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 10px;
font-style: normal;
font-weight: bold;
font-variant: normal;
color: #0099CC;
background-color: #FFFFCC;
border: 1px solid #FF9900;
}
.row1 {
background-color: #CCFFCC;
}
.style1 {
color: #FFFFFF;
font-weight: bold;
}
.row2 {
background-color: #FFFFFF;
}
-->
</style>
</head>

<body onLoad="javascript:attach_file( 'mysql_insert.php' ) ; show_status('Ready...'); ">
<table width="600" border="0" cellpadding="1" cellspacing="3" class="table1">
<tr>
<td width="88">Status Box: </td>
<td width="493" bgcolor="#CCCCCC"><span id="status" /></span> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Name</td>
<td><input name="u_name" type="text" id="u_name" size="40" maxlength="40"></td>
</tr>
<tr>
<td>Email</td>
<td><input name="u_email" type="text" id="u_email" size="40" maxlength="45">
(email MUST contain the '@' and '.') </td>
</tr>
<tr>
<td> </td>
<td><input type="button" name="Button" value="Click Here to Insert into Mysql..." onClick="javascript:attach_file( 'mysql_insert.php?u_name=' + u_name.value + '&u_email=' + u_email.value) ; show_status('Busy'); "></td>
</tr>
</table>

<br>
Data from MySQL: <br>

<!-- Do not remove this or the table will not show up -->
<span id="from_mysql">
</span>

<br>
</body>
</html>

'name the file below mysql_insert.php'

<?php
header( 'Content-Type: text/javascript' );
//database info: Change password and DB Name
$db = mysql_connect("localhost", "XXXX", "YYYY") or die (mysql_error());
mysql_select_db ("ZZZZ", $db) or die (mysql_error());

//get values if input fields
$u_name = addslashes($_GET['u_name']); //Name
$u_email = addslashes($_GET['u_email']); //Email

//If name and email are NOT empty, insert into mysql
if (strlen($u_name)>1 and strlen($u_email)>1 and strstr($u_email,"@") and strstr($u_email,".") ) {
$insert = mysql_query("INSERT INTO php_to_js (u_name, u_email) VALUES ('$u_name', '$u_email')",$db) or die(mysql_error());
}

//Now Refresh the table at the bottom id=from_mysql
$row_count = 0;
$output = '<table width="600" border="0" cellpadding="3" cellspacing="0" class="table1"><tr><td width="41" align="center" bgcolor="#3366CC"><span class="style1">Srno</span></td><td width="149" align="center" bgcolor="#3366CC"><span class="style1">Name</span></td><td width="384" align="center" bgcolor="#3366CC"><span class="style1">Email</span></td></tr>';
$result = mysql_query("SELECT srno, u_name, u_email FROM php_to_js",$db) or die (mysql_error());
While( $rows = mysql_fetch_array($result)) {
$srno = $rows['srno'];
$u_name = $rows['u_name'];
$u_email = $rows['u_email'];
$row_style = ($row_count % 2) ? "row1" : "row2";
$output .= '<tr class="'.$row_style.'"><td>'.$srno.'</td><td>'.$u_name.'</td><td>'.$u_email.'</td></tr>';
$row_count = $row_count + 1;
}
//Free Results
mysql_free_result($result);
$output .= '</table>';
?>

from_mysql_obj = document.getElementById( 'from_mysql' );
from_mysql_obj.innerHTML = '<? echo $output; ?>';


//update status box
my_status = document.getElementById( 'status' );
my_status.innerHTML = 'Ready...';

//clear values from text fields
document.getElementById('u_name').value = '';
document.getElementById('u_email').value = '';

Run "javatomysql.php" and input the proper email format.
you will see the new record added on database without refreshing the page!

commented: No point in keeping 2 seperate topics for the same issue going. +0

Ok. I don't see any significant difference here from this thread: http://www.daniweb.com/forums/thread185073.html so I'm going to shut this one down. I think there are too many replies in both threads to be able to merge them and have any semblance of continuity remain.

rm_daniweb, in the future restrict conversation on a particular topic to a single thread.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.