Hi. I have a calculate.js javascript file where all the function that execute the calculation is consist in this file. Now, I want to retrieve a data from the database for javascript calculation and be done in this calculate.js file. I have search a lot of methods to do this but most said cannot do this from a client-side. Is it possible? How to achieve this? Thanks in advance.

No. Most said correct. Database is in the server. Javascript works on client's machine. The only way is to have some script running on server (like php) that would retrieve data from database and pass it to javascript.

kracko, thanks for the reply. Can you show the example on how to retrieve data from database using php and pass it to javascript? Because I have to assign variable in javascript but the variable used for both php and javascript is different? Thanks in advance.

Hi. I have a calculate.js javascript file where all the function that execute the calculation is consist in this file. Now, I want to retrieve a data from the database for javascript calculation and be done in this calculate.js file. I have search a lot of methods to do this but most said cannot do this from a client-side. Is it possible? How to achieve this? Thanks in advance.

Microsoft has a proprietary solution:
http://msdn.microsoft.com/en-us/library/ms531385(VS.85).aspx

I've never tried this and don't know anyone who has.

I'm not aware of plugins for FireFox/Opera/Chrome but that doesn't mean they don't exist.

Airshow

Hi, this may or may not help ...

You have to make sure your database tables/fields line up between all these files and your database ... in this example I am using ID, username, and email to pull data in and out of an HTML file without a full page reload. Your HTML file needs to call an AJAX function which communicates with a PHP file that pulls data out of a MYSQL database. It "echos" back HTML into a specific area within the HTML file.

HERE IS PART OF THE HTML FILE .... (notice all Javascript files in the head section ... all of the onlclick functions within the HTML body can be found in the code below)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>abc123</title>
<link type="text/css" rel="stylesheet" href="bnk.css" />
<script type="text/javascript" src="utils.js"></script>
<script type="text/javascript" src="mctestpush.js"></script>
<script type="text/javascript" src="mctestpull.js"></script>
<script type="text/javascript" src="mctestremove.js"></script>
</head>
<body>
<h3>Input Transactions</h3>
<p>Input transactions here.</p>
<input type="text" id="username" name="username" />
<input type="text" id="email" name="email" />
<button type="button" onclick="mcpushdata()">pushdata</button>
<br />
<label for="rememail">Remove Data</label>
<input id="rememail" name="rememail" type="text" size="15" />
<button type="button" onclick="mcremovedata()">Remove</button><br />
<button type="button" onclick="mcshowdata()">showdata</button>
<div id="mcplacedata">
</div>
</body>
</html>

Here are the javascript files ....
mctestpull

function mcshowdata()
{
request = createRequest();
if (request==null){
	return;
	}
	
var url = 'mcgetalldata.php?+randNum=' + new Date().getTime();
request.open("GET",url,true);
request.onreadystatechange = displayDetails;
request.send(null);
}


function displayDetails() {
  if (request.readyState == 4) {
    if (request.status == 200) {
    
      mcplacedata.innerHTML = request.responseText;
    }
  }
}

mctestpush

function mcpushdata()
{
var usernamevalue = encodeURIComponent(document.getElementById("username").value)
var emailvalue = encodeURIComponent(document.getElementById("email").value)
var parameters = "username="+usernamevalue+"&email="+emailvalue

request = createRequest();
if (request==null){
	return;
	}

var pushurl = 'mcaddemail.php?+randNum=' + new Date().getTime();	
request.open("POST",pushurl,true);
request.onreadystatechange = displayDetails;
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
request.send(parameters);
}


function displayDetails() {
  if (request.readyState == 4) {
    if (request.status == 200) {
    
      mcplacedata.innerHTML = request.responseText;
    }
  }
}

mctestremove

function mcremovedata()
{
var emailval = encodeURIComponent(document.getElementById("rememail").value)
var param = "emailt="+emailval


request = createRequest();
if (request==null){
	return;
	}

var remurl = 'removeemailt.php?+randNum=' + new Date().getTime();	
request.open("POST",remurl,true);
request.onreadystatechange = displayDetails;
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
request.send(param);
}


function displayDetails() {
  if (request.readyState == 4) {
    if (request.status == 200) {
    
      mcplacedata.innerHTML = request.responseText;
    }
  }
}

utils js file

function createRequest() {
  try {
    request = new XMLHttpRequest();
  } catch (tryMS) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (otherMS) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = null;
      }
    }
  }	
  return request;
}

Now all the php files that connect to the server to insert and pull back data ...

You have to have all the right info in the mysql_connect PHP function to connect to your own database.

mcaddemail.php

<?php
  $dbc = mysqli_connect('localhost', 'aaa', 'aaa', 'aaa')
    or die('Error connecting to MySQL server.');

  $user_name = $_POST['username'];
  $email = $_POST['email'];

  $query = "INSERT INTO email_list (user_name, email)  VALUES ('$username', '$email')";
  mysqli_query($dbc, $query)
    or die('Error querying database.');



$con = mysql_connect('aaa', 'aaa', 'aaa');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("aaa", $con);

$result = mysql_query("SELECT * FROM email_list order by id desc");

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['id'] . "</td>";
    echo " ---- ";
    echo "<td>" . $row['user_name'] . "</td>";
    echo " ---- ";
    echo "<td>" . $row['email'] . "</td>";
    echo "<br />";
  echo "</tr>";
  }

mysql_close($con);
?>

</body>
</html>

mcgetalldata

<?php
$con = mysql_connect('aaa', 'aaa', 'aaa');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("aaa", $con);

$result = mysql_query("SELECT * FROM email_list order by id desc");

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['id'] . "</td>";
    echo " ---- ";
    echo "<td>" . $row['user_name'] . "</td>";
    echo " ---- ";
    echo "<td>" . $row['email'] . "</td>";
    echo "<br />";
  echo "</tr>";
  }

mysql_close($con);
?>

removeemail

<?php
   $dbc = mysqli_connect('aaa', 'aaa', 'aaa', 'aaa')
    or die('Error connecting to MySQL server.');

  $email = $_POST['emailt'];

  $query = "DELETE FROM email_list WHERE email = '$email'";
  mysqli_query($dbc, $query)
    or die('Error querying database.');

 $con = mysql_connect('aaa', 'aaal', 'aaa');
 if (!$con)
   {
   die('Could not connect: ' . mysql_error());
   }

 mysql_select_db("aaa", $con);

 $result = mysql_query("SELECT * FROM email_list order by id desc");

 while($row = mysql_fetch_array($result))
   {
   echo "<tr>";
   echo "<td>" . $row['id'] . "</td>";
     echo " ---- ";
     echo "<td>" . $row['user_name'] . "</td>";
     echo " ---- ";
     echo "<td>" . $row['email'] . "</td>";
     echo "<br />";
   echo "</tr>";
   }

mysql_close($con);
?>

</body>
</html>

hi, well m not sure that it will work but it should be.
the solution comes to my mind is you need data in JS variables and you have it in php variable. so what u can do is, simply execute the query and get data from the database. no let say u had fields id,name and age. you have it in $row after executing mysql_fetch_array().
now close php code here for now now in javascript code, use

var id=<?php echo $row;?>;
var name="<?php echo $row;?>";
var age=<?php echo $row;?>;

this should work as php executes at server side so when the page is rendered the php echo statement should have printed the text there and js shouldn't have any problem in assigning it. hope it will work.

Hi, mikecronauer. Thanks for the details example. But can you show me the way to do calculation? Because I have to retrieve data from database for calculation. For example, the data that I retrieved from database is $a (php), then I have to use this value in javascipt calculation.

for example, this is the code that I have to write in calculate.js file.

var payment = document.getElementById("paymentA").value = (document.getElementById("paymentB").value * ($a/100));

although I know this can't work but this is something that I have to do with. So do you have any ideas or example on this? Thanks in advance.

Hi, this may or may not help ...

You have to make sure your database tables/fields line up between all these files and your database ... in this example I am using ID, username, and email to pull data in and out of an HTML file without a full page reload. Your HTML file needs to call an AJAX function which communicates with a PHP file that pulls data out of a MYSQL database. It "echos" back HTML into a specific area within the HTML file.

HERE IS PART OF THE HTML FILE .... (notice all Javascript files in the head section ... all of the onlclick functions within the HTML body can be found in the code below)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>abc123</title>
<link type="text/css" rel="stylesheet" href="bnk.css" />
<script type="text/javascript" src="utils.js"></script>
<script type="text/javascript" src="mctestpush.js"></script>
<script type="text/javascript" src="mctestpull.js"></script>
<script type="text/javascript" src="mctestremove.js"></script>
</head>
<body>
<h3>Input Transactions</h3>
<p>Input transactions here.</p>
<input type="text" id="username" name="username" />
<input type="text" id="email" name="email" />
<button type="button" onclick="mcpushdata()">pushdata</button>
<br />
<label for="rememail">Remove Data</label>
<input id="rememail" name="rememail" type="text" size="15" />
<button type="button" onclick="mcremovedata()">Remove</button><br />
<button type="button" onclick="mcshowdata()">showdata</button>
<div id="mcplacedata">
</div>
</body>
</html>

Here are the javascript files ....
mctestpull

function mcshowdata()
{
request = createRequest();
if (request==null){
	return;
	}
	
var url = 'mcgetalldata.php?+randNum=' + new Date().getTime();
request.open("GET",url,true);
request.onreadystatechange = displayDetails;
request.send(null);
}


function displayDetails() {
  if (request.readyState == 4) {
    if (request.status == 200) {
    
      mcplacedata.innerHTML = request.responseText;
    }
  }
}

mctestpush

function mcpushdata()
{
var usernamevalue = encodeURIComponent(document.getElementById("username").value)
var emailvalue = encodeURIComponent(document.getElementById("email").value)
var parameters = "username="+usernamevalue+"&email="+emailvalue

request = createRequest();
if (request==null){
	return;
	}

var pushurl = 'mcaddemail.php?+randNum=' + new Date().getTime();	
request.open("POST",pushurl,true);
request.onreadystatechange = displayDetails;
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
request.send(parameters);
}


function displayDetails() {
  if (request.readyState == 4) {
    if (request.status == 200) {
    
      mcplacedata.innerHTML = request.responseText;
    }
  }
}

mctestremove

function mcremovedata()
{
var emailval = encodeURIComponent(document.getElementById("rememail").value)
var param = "emailt="+emailval


request = createRequest();
if (request==null){
	return;
	}

var remurl = 'removeemailt.php?+randNum=' + new Date().getTime();	
request.open("POST",remurl,true);
request.onreadystatechange = displayDetails;
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
request.send(param);
}


function displayDetails() {
  if (request.readyState == 4) {
    if (request.status == 200) {
    
      mcplacedata.innerHTML = request.responseText;
    }
  }
}

utils js file

function createRequest() {
  try {
    request = new XMLHttpRequest();
  } catch (tryMS) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (otherMS) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = null;
      }
    }
  }	
  return request;
}

Now all the php files that connect to the server to insert and pull back data ...

You have to have all the right info in the mysql_connect PHP function to connect to your own database.

mcaddemail.php

<?php
  $dbc = mysqli_connect('localhost', 'aaa', 'aaa', 'aaa')
    or die('Error connecting to MySQL server.');

  $user_name = $_POST['username'];
  $email = $_POST['email'];

  $query = "INSERT INTO email_list (user_name, email)  VALUES ('$username', '$email')";
  mysqli_query($dbc, $query)
    or die('Error querying database.');



$con = mysql_connect('aaa', 'aaa', 'aaa');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("aaa", $con);

$result = mysql_query("SELECT * FROM email_list order by id desc");

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['id'] . "</td>";
    echo " ---- ";
    echo "<td>" . $row['user_name'] . "</td>";
    echo " ---- ";
    echo "<td>" . $row['email'] . "</td>";
    echo "<br />";
  echo "</tr>";
  }

mysql_close($con);
?>

</body>
</html>

mcgetalldata

<?php
$con = mysql_connect('aaa', 'aaa', 'aaa');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("aaa", $con);

$result = mysql_query("SELECT * FROM email_list order by id desc");

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['id'] . "</td>";
    echo " ---- ";
    echo "<td>" . $row['user_name'] . "</td>";
    echo " ---- ";
    echo "<td>" . $row['email'] . "</td>";
    echo "<br />";
  echo "</tr>";
  }

mysql_close($con);
?>

removeemail

<?php
   $dbc = mysqli_connect('aaa', 'aaa', 'aaa', 'aaa')
    or die('Error connecting to MySQL server.');

  $email = $_POST['emailt'];

  $query = "DELETE FROM email_list WHERE email = '$email'";
  mysqli_query($dbc, $query)
    or die('Error querying database.');

 $con = mysql_connect('aaa', 'aaal', 'aaa');
 if (!$con)
   {
   die('Could not connect: ' . mysql_error());
   }

 mysql_select_db("aaa", $con);

 $result = mysql_query("SELECT * FROM email_list order by id desc");

 while($row = mysql_fetch_array($result))
   {
   echo "<tr>";
   echo "<td>" . $row['id'] . "</td>";
     echo " ---- ";
     echo "<td>" . $row['user_name'] . "</td>";
     echo " ---- ";
     echo "<td>" . $row['email'] . "</td>";
     echo "<br />";
   echo "</tr>";
   }

mysql_close($con);
?>

</body>
</html>

Hi, Saqib_J. Thanks for the reply. But the php and javascript cannot be used in the same time. So do you have another solution? Thanks in advance.

hi, well m not sure that it will work but it should be.
the solution comes to my mind is you need data in JS variables and you have it in php variable. so what u can do is, simply execute the query and get data from the database. no let say u had fields id,name and age. you have it in $row after executing mysql_fetch_array().
now close php code here for now now in javascript code, use

var id=<?php echo $row;?>;
var name="<?php echo $row;?>";
var age=<?php echo $row;?>;

this should work as php executes at server side so when the page is rendered the php echo statement should have printed the text there and js shouldn't have any problem in assigning it. hope it will work.

Star_lavender,

.... But the php and javascript cannot be used in the same time.

You have all the information you need.

  1. Put your thinking head on.
  2. Read Saqib_J's post all the way through - last paragraph explains.
  3. Once you have grasped the concept (php can write javascript, same as it writes HTML), use it to write (in part) your line of javascript var payment = document.getElementById("paymentA").value = (document.getElementById("paymentB").value * ($a/100)); .

You will then have a line of javascript comprising mainly hard-code but including a value (originally php variable $a) determined and written into the statement server-side before the page is served.

I could write it for you in about 15 seconds but you will learn more from working it out yourself.

Airshow

Thanks for the help and now I manage to retrieve the data that I am needed from database. Then the data will be used in calculation. But now the system will read the correct value and path after the calculate button is clicked but not work with the others code.
Part of the codes.

Javascript code

<script type="text/javascript">
function a()
{
    var a= "<?php echo $ax; ?>";
    var b= "<?php echo $bx; ?>";
    var c= "<?php echo $cx; ?>";
    var d= "<?php echo $dx; ?>";

    if(c== "xxx")
    {
        abc();
    }
                                            
    else if(c== "yyy")
    {
        def(); 
    }                    
}
function abc()
{
    if(a == "")
    {
        if(b == "Yes")
        {
           //some coding here
        }
        
        else if(b == "")
        {
            //some coding here
        }
    }

    else if(a == "Yes")
    { 
        if(b == "Yes")
        {//alert("hi"); For example, I try to pop up a msg here, then it got run but the rest of the coding not working..every line same.the got read the correct condition but didn't execute
            var ab = document.getElementById("x").value;
            var cd = document.getElementById("y").value = (d * (ab/100));
            document.getElementById("y").value = cd.toFixed(2);
            
            //some coding here            
            if(document.main.zzz.options[document.main.zzz.selectedIndex].value == "xy")
            {
                var ef = document.getElementById("t").value = ((document.getElementById("s").value - document.getElementById("o").value)*(50/100));
                //some coding here
            }
            
            else if(document.main.zzz.options[document.main.zzz.selectedIndex].value == "st")
            {
                //some coding here
            }
        }
        
        else if(b == "")
        {            
            //some coding here
        }
    }
}
function def()
{
   //some coding here
}

php code

<table border="1" align="center">
<tr>
<td align="center"><input type="button" name="calculate" value="Calculate" onClick="a()"></td>
<td align="center"><input type="submit" name="submit" value="Submit"></td>
<td align="center"><input type="reset" name="reset" value="Reset"></td>
</tr>
</table>

Thanks in advance for any advice and solution.

Star_lavender,

You're nearly there.

Now it's just a question of either (a) declaring the variables a,b,c,d in the global scope, or (b) passing the variables a,b,c,d to the other functions like this :

function a(){
    var a= "<?php echo $ax; ?>";
    var b= "<?php echo $bx; ?>";
    var c= "<?php echo $cx; ?>";
    var d= "<?php echo $dx; ?>";
    if(c== "xxx") { abc(a, b, c, d); }
    else if(c== "yyy") { def(a, b, c, d); }
}
.....

You might also like to consider making your variables observable by writing them into the HTML like this:

a: <input id="myVarA" type="text" value="<?php echo $ax; ?>" /><br />
b: <input id="myVarB" type="text" value="<?php echo $bx; ?>" /><br />
c: <input id="myVarC" type="text" value="<?php echo $cx; ?>" /><br />
d: <input id="myVarD" type="text" value="<?php echo $dx; ?>" /><br />

Now you can grab the values in javascript with a further modification of function a() :

function a(){
    var a = document.getElementById('myVarA').value;
    var b = document.getElementById('myVarB').value;
    var c = document.getElementById('myVarC').value;
    var d = document.getElementById('myVarD').value;
    if(c== "xxx") { abc(a,b,c,d); }
    else if(c== "yyy") { def(a,b,c,d); }
}

You will find this formulation useful for testing as you can now type values directly into the input fields (myVarA, myVarB, myVarC, myVarD).

When you have finished testing, you can hide the input fields by changing type="text" to type="hidden" and everything else will still work.

Airshow

thanks for all the help , solutions and advices. my problem solved already. thanks again.

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.